Answer the question
In order to leave comments, you need to log in
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();
});
public function scopeUser(Builder $query, $value): Builder
{
return $query->where(
'user_id',
'=',
Uuid::isValid($value) ? $value : User::whereNickname($value)->firstOrFail()->getKey()
);
}
public function scopeUser(Builder $query, User $user): Builder
{
return $query->where('user_id', '=', $user->getKey());
}
Answer the question
In order to leave comments, you need to log in
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
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question