Dicky Raambo
Dicky Raambo

Reputation: 523

Laravel 5.5 eloquent one-to-many not work using get()

I have one to many relationships and need to show using where conditions.

When I use findOrFail() it's working as well.

$foo = Model::findOrFail(1);

on my template blade

@foreach($foo->bars as $index=>$bar)

   {{ $bar->name }}

@endforeach

on my code above, it's working. but the reference to an id, that's not what I need.

I need it using where conditions. like this:

$foo = Model::where('conditon', 1)->get();

then I call it on my blade template with

@foreach($foo->bars as $index=>$bar)

   {{ $bar->name }}

@endforeach

then I get an error:

ErrorException (E_ERROR) Property [bars] does not exist on this collection instance.

It seems after get() I cannot call child with $foo->bars

How do you get this to work?

Upvotes: 1

Views: 95

Answers (3)

N69S
N69S

Reputation: 17206

The findOrFail() method returns an instance of the "Model". The get() method returns a collection of instances of the "Model" even if there is only one result.

if you want just one result, use first() instead of get().

$foo = Model::where('conditon', 1)->first();

then in the blade template do

@if($foo)
    @foreach($foo->bars as $index=>$bar)

       {{ $bar->name }}

    @endforeach
@endif

if you need multiple results, do another foreach().

@foreach($foo as $oneFoo)

    @foreach($oneFoo->bars as $index=>$bar)

        {{ $bar->name }}

    @endforeach

@endforeach

if you are going with the "multiple" solution, i suggest you name your variable "foos".

$foos = Model::where('conditon', 1)->get();

and so

@foreach($foos as $foo)

    @foreach($foo->bars as $index=>$bar)

        {{ $bar->name }}

    @endforeach

@endforeach

Upvotes: 1

Ron van der Heijden
Ron van der Heijden

Reputation: 15070

Because ->get() retrieve multiple results which fit the query criteria.

You can either loop through $foo results or use ->first() to retreive the first query match.

Upvotes: 1

Egretos
Egretos

Reputation: 1175

Try to use ->first() instead of ->get().

Upvotes: 1

Related Questions