Reputation: 301
I have a collection which I have extracted from the database using the findMany method in eloquent. When I dd the collection it looks like the attached image. And then I am trying to (in my blade) loop through each item in the array such that I am able to print each of the values in the actual records.
$question = Question::whereIn('id', [23,25])->get();
Then in my blade I am trying to do:
@foreach ($question as $row => $innerArray)
@foreach ($innerArray as $innerRow => $value)
{{$value->question}} //I was expecting "What is your favourite food" here
@foreach ($value->option as $choice)
<li>{{$choice}}</li> //I was expecting the list of the options here
@endforeach
@endforeach
@endforeach
What am I doing wrong?
Upvotes: 1
Views: 7387
Reputation: 1931
All multi-result sets returned by Eloquent are instances of the Illuminate\Database\Eloquent\Collection
object, including results retrieved via the get method or accessed via a relationship. The Eloquent collection object extends the Laravel base collection, so it naturally inherits dozens of methods used to fluently work with the underlying array of Eloquent models.
All collections also serve as iterators, allowing you to loop over them as if they were simple PHP arrays:
$questions = Question::whereIn('id', [23, 25, ..])->get();
foreach ($questions as $question) {
echo $question->title; // What is your favourite food
echo $question->name; // food
foreach ($question->options as $option) {
echo $option; // Pizza
}
}
Upvotes: 1
Reputation: 3805
The correct syntax is this:
@foreach ($question as $q)
{{ $q->question }} //I was expecting "What is your favourite food" here
@foreach ($q->options as $choice)
<li>{{$choice}}</li> //I was expecting the list of the options here
@endforeach
@endforeach
Upvotes: 1