Home > Blockchain >  how to display data from different table using id laravel 8
how to display data from different table using id laravel 8

Time:11-08

I have 2 tables, assets and phistories. in table phistories will carry asset_id. i want to display phistories list that under selected asset_id. What i've tried so far in the AssetController:

public function edit(Asset $asset)
    {
        $phistories = (DB::table('phistories')->where('asset_id',$asset)->get()); 
        
        return view('assets.editAsset',[
            'asset' => $asset,
            'phistories' => $phistories
        ]);
    }

this is my view

 @foreach($phistories as $phistory)
      <tr>
        <td>{{$phistory->id}}</td>
        <td><a href="/edit/{{$phistory->id}}/editPhistory"><span>{{$phistory->phistory_name}}</span></a>
        </td>
        <td>{{$phistory->phistory_category}}</td>
        <td>{{$phistory->phistory_pic}}</td>
      </tr>
 @endforeach

My problem is it did not display anything in the view. can anyone check my query is it correct or not or i used a wrong method?

CodePudding user response:

Assuming you have a model named Assets and Phistories, you need to write a many-to-many relationship inside those models. i.e.

In your Assets model, add this function;

    public function phistories()
    {
        return $this->belongsToMany(Phistories::class);
    }

Once the relationship is defined, you may access the Phistories using the phistories dynamic relationship property from your Assets controller:

use App\Models\Assets;
public function edit(Asset $asset)
    {

        $assets = Assets::with('phistories');
        
        return view('assets.editAsset',['assets' => $assets]);
    }

Use this if you want to be able to access Assets from the Phistories model

In your Phistories model, add this relationship;

    public function Assets()
    {
        return $this->belongsToMany(Assets::class);
    }

Now, Inside your view, you can access the Phistories data like so,

@foreach($assets as $asset)
      <tr>
        <td>{{$asset->id}}</td>
        @foreach($asset->phistories as $phistory)
            <td>
               <a href="/edit/{{$phistory->id}}/editPhistory">
                 <span>{{$phistory->phistory_name}}</span>
               </a>
            </td>
        @endforeach
      </tr>

@endforeach

CodePudding user response:

$phistories = (DB::table('phistories')->where('asset_id',$asset)->get());

to change

$phistories = (DB::table('phistories')->wherein('asset_id',$asset)->get());

if $asset is multiple id's

and second please try first() insted of get()

  • Related