Ad

ManytoMany Relations In Laravel, Retrieve Data From Related Tables And Display In Blade

- 1 answer

I have two tables related by many to many relation in Laravel Framework. I can display data from each table separately, but not through relation by taking one record from the 1st table and checking related records in the 2nd table. In tinker it accesses data fine.

Relations:

public function underperformances() {
        return $this->belongsToMany(Underperformance::Class);
    }
...
  public function procedures() {
        return $this->belongsToMany(Procedure::class);
    }

My resource controller part:

...
use App\Underperformance;
use App\Procedure;
...

public function index()
  {
       $books = Underperformance::orderBy('id','desc')->paginate(9);
       $procedures = Procedure::all();
       return view('underpcon.underps', compact('books', 'procedures'));
   }

Route:

Route::get('/underps', '[email protected]');

If I try to display data like this:

@foreach($procedures as $procedure) 
  <li>{{$procedure->underperformances}}</li>
 @endforeach

I get such format to the browser:

[{"id":1,"title":"Spare part not taken before service","description":"tekstas","level":"1","costs":600 ...

This is correct data from related table, but I cannot select further the specific column from that table. For example this does not work:

@foreach($procedures as $procedure) 
  <li>{{$procedure->underperformances->id}}</li>
 @endforeach

Nor this one:

 @foreach ($procedures->underperformances as $underperformance) 
 <li>{{$underperformance->id}}</li>
@endforeach
  1. How do I select records of the related table and display specific data from that table?
  2. What would be a conventional way to do this?
Ad

Answer

@foreach($procedures as $procedure) 
  <li>{{$procedure->underperformances->id}}</li>
 @endforeach

^ This right there $procedure->underperformances will return a collection, not a single item, so you need to treat it as array, you will not be able to access the id directly, you can either @foreach that, or use the pluck method in Laravel Collections.

Ad
source: stackoverflow.com
Ad