I try to show nested array with blade in Laravel 5.1 but I can't do this :
Controller:
public function track($id){
$tracks = track::with('trials.samples')->where('trials_id',$id)->get();
//return $tracks;
return view('Tracks.index',compact('tracks'));
}
Traks.index:
{{ $track['samples']['variety'] }}
return $tracks return:
[{"id":1,"trials_id":1,"date":"2015-12-16","comments":"\u0646\u062a\u06cc\u062c\u0647 \u062e\u0627\u0635\u06cc \u0646\u062f\u0627\u0634\u062a\u0647 !","created_at":"-0001-11-30 00:00:00","updated_at":"-0001-11-30 00:00:00","trials":{"id":1,"persons_id":1,"samples_id":1,"amount":"125000","date":"2015-12-09","comments":"","code":"5CEPY","created_at":"2015-12-08 06:46:58","updated_at":"2015-12-08 06:46:58","samples":{"id":1,"variety":"keyhan","supplier_id":1,"lot_number":"2550","date":"2015-12-11","amount":125000,"unit_id":1,"technical_fact":"\u0641\u0646\u06cc","comments":"1","file_address":"","category_id":1,"created_at":"2015-12-08 06:46:34","updated_at":"2015-12-08 06:46:34"}}}]
I tried this code too, but nothing is showing:
{{ $track['trials.samples']['variety'] }}
{{ $track->samples['variety'] }}
First, I've never used compact()
to return anything to a view, so I am unfamiliar with it's usage.
However, you can use with()
to return stuff to a view, so if you change that line to:
return view('Tracks.index')->with(["tracks" => $tracks]);
You can then show them in the blade using a @foreach
loop, or accessing the first element using $tracks[0]...
. For example:
@foreach($tracks AS $track)
{{ $track->comments }}
@foreach($track->trials AS $trial)
{{ $trial->code }}
@foreach($trial->samples AS $sample)
{{ $sample->variety }}
@endforeach
@endforeach
@endforeach
Note, this depends on how your relationships are set up in your Track
, Trial
and Sample
models. For example:
public function trials(){
return $this->hasMany("App\Trial")->get();
// vs
return $this->hasOne("App\Trial")->first();
}
In the event of ->get()
, you would have to use the @foreach
syntax to access it, but if you were only expecting one result you could simply use:
{{ $track->trials->samples->variety }}
If you need more information, check out Laravel's documentation: Blade Documentation and Eloquent Collections