Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

luddinus's avatar

Eager load with parameters

Hi.

How can I add a parameters for eager load one relationship?

User model

public function someRelation($required_parameter)
{
    return $this->hasMany('SomeModel')->where('required_parameter', $required_parameter);
}

SomeWhatever.php

User::with(['someRelation'])->get();

// something like this?
// User::with(['someRelation' => [$requiredParameter])->get();
0 likes
5 replies
pmall's avatar

Relationships does not expect to take parameters. Why are you doing this.

luddinus's avatar

@pmall I have a polymorphic relation (notifications) and "friend requests" between some users

notification table would have the notificable_id (request_id in this case)

user_id = $user_id;
notificable_type = 'friend_request';
notificable_id = $friend_request_id;

I need to know the user_id (the required parameters) because user_id would be the user who "receives" the friend request and the same with the user response to that request.

So, to do that, I need to do

$friend_request->notification($user_id)->first();
// OR
$request->notification()->whereUserId($user_id); // I think this would be the right way and pass a Closure when eager load
JarekTkaczyk's avatar

@luddinus You can create parametrized method that will return closure used in eager loading.

public static function getSomeClosure($param) // might be static or instance method
{
    return function ($query) use ($param) {
        $query->where('column', $param);
    };
}

then

User::with(['someRelation' => User::getSomeClosure($yourParam)])->get();

but obviously this can be done inline as well:

User::with(['someRelation' => function ($q) use ($yourParam) {
    $q->where('column', $yourParam);
}])->get();
10 likes
samsoft's avatar
Partner::with('partnership', 'contributionType', 'modeOfPayment', 'state')->get();

OR

Partner::where('id', '=', $id)
            ->with('partnership', 'contributionType', 'modeOfPayment', 'state')
            ->get();

Please or to participate in this conversation.