t0berius's avatar

load attributes after route model binding

I'm using route model binding to load basic relationships & attributes for models like:

    Route::bind('frontendConversation', function ($value) {
        $conversation = \App\Models\Conversation::where('id', $value)->with(['involvedUsers', 'sender:id,slug,name',])->firstOrFail();

        return $conversation;

    });

Inside a controller action I would need to have access to the level attribute of sender, like:

$conversation->sender->level

is there a way how I can load only this specific attribute from inside the controller?

Since it's only required in certain circumstances it won't make sense to modify the route model binding.

0 likes
2 replies
LaryAI's avatar
Level 58

To load only the specific attribute level from the sender relationship inside the controller, you can make use of the load() method provided by Laravel's Eloquent ORM.

Here's an example of how you can modify your controller action to load only the level attribute:

public function show(Conversation $frontendConversation)
{
    $frontendConversation->load('sender:level');

    // Now you can access the `level` attribute of the `sender` relationship
    $level = $frontendConversation->sender->level;

    // Rest of your code...

    return view('conversation.show', compact('frontendConversation'));
}

In the above example, the load() method is used to eager load the sender relationship with only the level attribute. This will ensure that only the level attribute is loaded for the sender relationship, reducing unnecessary database queries.

Note that you need to make sure that the sender relationship is defined in your Conversation model using the belongsTo method.

public function sender()
{
    return $this->belongsTo(User::class);
}

By using this approach, you can selectively load specific attributes for relationships when needed, without modifying the route model binding.

tisuchi's avatar

@t0berius Simply you can do this in the method as @laryai explained.

// This will perform an additional query if 'level' is not already loaded.
$frontendConversation->loadMissing('sender.level');

// Now you can access the 'level' attribute.
$level = $frontendConversation->sender->level;

Please or to participate in this conversation.