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.
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.
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?
Changed to
class Operator extends Model
{
//
public function country()
{
return $this->belongsTo('App\Country');
}
}
but I'm getting same behavior ..?
Which version are you using? Im developing in 5.2 and I dont get that wierd result
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community