Support the ongoing development of Laravel.io →
Database Eloquent Queues
Last updated 1 year ago.
0

First of all I'm going to guess you are using dependency injection like this:

public function view(Country $country)
{    
    .....
    .....
    ....
}

In this case you need to use, Lazy Eager Loading. Here is the definition from the official documentation.

Lazy Eager Loading

Sometimes you may need to eager load a relationship after the parent model has already been retrieved. For example, this may be useful if you need to dynamically decide whether to load related models.

In this case, you already injected your model into your controller:

public function view(Country $country)
{
    $country->load('operators')->get();
    return view('yourview', compact('country')) 
}

In the code above you will only get the relationship from the selected country.

In the other hand, using:

public function view(Country $country)
{
    $country = App\country::where('id',1)->with('operators')->get();
    return view('yourview', compact('country')) 
}

In the code above you are instantiating a new model Country... So laravel is retrieving everything from the DB not only your selected country. Thats the reason you have to pass the where clause to only filter the country needed.

I hope this helps.

0

Thank You very much! Lazy Eager loading what the solution

but when I do

return $country->load('operators')

I get desired 1 country

but

return $country->load('operators')->get()

retuns again all countries.

Why it is like that?

Yes I'm using dep injection.

Last updated 7 years ago.
0

Quick question... Why your relationship between Operator to Country is belongsToOne???

class Operator extends Model
{
    //
    public function country()
    {
        return $this->belongsToOne('App\Country');
    }
}

It should be, belongsTo

class Operator extends Model
{
    //
    public function country()
    {
        return $this->belongsTo('App\Country');
    }
}

could that be the problem?

0

Changed to

class Operator extends Model
{
    //
    public function country()
    {
        return $this->belongsTo('App\Country');
    }
}

but I'm getting same behavior ..?

0

Which version are you using? Im developing in 5.2 and I dont get that wierd result

0

Sign in to participate in this thread!

Eventy

Your banner here too?

visualus visualus Joined 16 Sep 2016

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.