Abdallah Sakre
Abdallah Sakre

Reputation: 915

Looping through an array of a query inside a blade

I'm trying to loop through an array for a query written in the blade, as follows :

@foreach({{\App\Post::where('qid',$updt_18_q->qid)->get()->body}} as $updt_18_a)

I'm receiving the following error :

syntax error, unexpected '<'

The query is working fine by using first() outside the @foreach loop.

Upvotes: 1

Views: 136

Answers (3)

Nick
Nick

Reputation: 546

@foreach(\App\Post::where('qid',$updt_18_q->qid)->get()->body ?? [] as $updt_18_a)
//code
@endforeach

Upvotes: 1

akshaypjoshi
akshaypjoshi

Reputation: 1295

get() method in Laravel returns an array of objects and first() method returns single object. That's why your query is working with first().

So you need to do this :

// This is your array of objects.
@php($posts = \App\Post::where('qid',$updt_18_q->qid)->get())

// Iterate through array
// $updt_18_a is your Post object
/* $updt_18_a \App\Post */
@foreach($posts as $updt_18_a)
 $body = $updt_18_a->body; // Access like this.
 // Code here
@endforeach

Upvotes: 1

BlackXero
BlackXero

Reputation: 880

What you are doing is so bad practice, write all your logic in Controller

{{}}

The above syntax is for echoing something so you are not looping an array but echoing it do it like this

In Laraval if you echo an array or object it automatically convert's it into json Object so you won't get array to string conversion error

@php $data = \App\Post::where('qid',$updt_18_q->qid)->get() @endphp

@foreach($data as $updt_18_a)
//code
@endforeach

Upvotes: 1

Related Questions