A
A
Artem00712020-05-17 18:23:43
Laravel
Artem0071, 2020-05-17 18:23:43

Model binding in Laravel?

The lara has a built-in route binding
But is there one for regular injections?

There is a user who can be found either by ID or by nickname
. In the route, this is implemented as follows:

Route::bind('user', static function ($value) {
            return Uuid::isValid($value)
                ? User::whereId($value)->firstOrFail()
                : User::whereNickname($value)->firstOrFail();
        });


There are other modules in which the user participates.
So, there are scopes for these models:
public function scopeUser(Builder $query, $value): Builder
    {
        return $query->where(
            'user_id',
            '=',
            Uuid::isValid($value) ? $value : User::whereNickname($value)->firstOrFail()->getKey()
        );
    }


And such a canoe from class to class

It could be done like this:
public function scopeUser(Builder $query, User $user): Builder
    {
        return $query->where('user_id', '=', $user->getKey());
    }


But here the problem is that this is either a nickname or an ID. Is it possible to somehow register these binds somewhere as it is implemented for the router?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Aksentiev, 2020-05-18
@Artem0071

As for me, the best option is to get the user first, and then use him in scopes, etc.
Instead of throwing a random string into the scopes and let him figure out what to do with it.
It is much better not to write down in any way, except whereHas to attach for greater readability.
And then it will not be necessary to get the user in advance and an extra request will not be made in principle, although the request itself with whereHas will be heavier.

And such a canoe from class to class

This is treated with a trait to avoid code duplication.
What is the original problem and did not understand.
In that it is necessary to somehow bind conveniently or not to do in each scopeUser () model.
So, in general, you can come up with some kind of resolver for model binds, but apparently it's like a cannon on sparrows.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question