AlexNastase's avatar

Query in accesor

Hi guys, it is ok to use querys in accesors?

Example: I want to get the user model instead of the user ID. I will use that accesor in a user pagination page too. The laravel debug bar is not showing the query(s) from the accesor and i'm not sure if should use that accesor or not.

In Controller:

$conversations = Conversation::with('messages')
            ->where('user_one', $user->id)
            ->orWhere('user_two', $user->id)
            ->paginate(6);

In Model:

public function getUserOneAttribute($value)
    {
        $user = User::where('id', $value)->firstOrFail();
        return $user;
    }

    public function getUserTwoAttribute($value)
    {
        $user = User::where('id', $value)->firstOrFail();
        return $user;
    }
0 likes
4 replies
tykus's avatar

I want to get the user model instead of the user ID

You will want to be careful about messing with the identity...

There is nothing to execute the mutator unless the property is called on the object, or you are appending auomatically whwnever you represent the model as an array.

AlexNastase's avatar

@tykus

Thank you for your response.

I have added the controller and model codes too.

tykus's avatar
tykus
Best Answer
Level 104

Seems to me to be a use case for relationships rather than accessor attributes:

// Conversation Model

public function userOne()
{
    return $this->belongsTo(User::class, 'user_one');
}

public function userTwo()
{
    return $this->belongsTo(User::class, 'user_one');
}

// bonus scope
public function scopeWithParticipant(Builder $builder, User $user)
{
    return $builder->where('user_one', $user->id)
            ->orWhere('user_two', $user->id);
}

Your Eloquent query would look like this:

$conversations = Conversation::with(['messages', 'userOne', 'userTwo'])
            ->withParticipant($user)
            ->paginate(6);
2 likes

Please or to participate in this conversation.