NoLAstNamE's avatar

Is Eager load is still loaded even if it's passed in another method?

I'm asking this straight to Laracasts, is the eager-loaded relationship still loaded even if it's being passed to another method?

I have this on my controller:

public function approve(Task $task, Request $request)
{
    // here we load the user relationship
    $task = $task->load('user');
    
    // and now we pass the task to another method to do something
    $this->doSomething($task);
}

public static function doSomething(Task $task)
{
    // is the user relationship still loaded here?
    // do something here
}
0 likes
4 replies
LaryAI's avatar
Level 58

Yes, the eager-loaded relationship is still loaded even if it's being passed to another method. In the provided code example, the user relationship is loaded on the $task model instance in the approve method using the load method. When the $task instance is passed to the doSomething method, the user relationship will still be loaded and accessible on the $task instance.

Here's an example to demonstrate this:

public function approve(Task $task, Request $request)
{
    // here we load the user relationship
    $task = $task->load('user');
    
    // and now we pass the task to another method to do something
    $this->doSomething($task);
}

public static function doSomething(Task $task)
{
    // is the user relationship still loaded here?
    // do something here
    $user = $task->user; // the user relationship is still loaded and accessible
}
2 likes
nexxai's avatar

@benjamin1509 Yes, the AI's response is correct. Any eager-loaded relationship data is passed along with any data you feed to another method as a parameter.

1 like

Please or to participate in this conversation.