My db structure is
Profile
- ID ..
Profile_row
- ID
- Name: eks “First_name”
- Content: eks “James”
- Profile_id: 1
In my controller I do this:
$profiles = Profile::with('profile_row')->paginate($request->per_page);
and my Profile Model looks like this
public function profile_row() { return $this->hasMany('AppProfileRow')->where('name', 'first_name'); }
And I get a nice nested list with profiles, and every profile_row where name=first_name under.
But how can I send a argument from the controller to the Model where I define what profile row ‘name’ I want to return?
Eks: Controller (This don’t work, but I hope it will show what I’m after)
$profiles = Profile::with('profile_row('first_name')')->paginate($request->per_page);
Model:
public function profile_row($name) { return $this->hasMany('AppProfileRow')->where('name', $name); }
Advertisement
Answer
Alter you profile_row
model’s method to be whithout the name
parameters:
public function profile_row() { return $this->hasMany('AppProfileRow'); }
When you load relationship with the with
method add the constraint there.
$profiles = Profile::with(['profile_row'=>function($query) use($name) { $query->where('name', $name); }])->paginate($request->per_page);
From the doc https://laravel.com/docs/8.x/eloquent-relationships#constraining-eager-loads