I've seen the following route:
Route::prefix('/users/{user}')->group(function () {
Route::get('groups/{group}', 'UserGroupController@show');
}
And in UserGroupController:
use App\Group;
public function show(Request $request, User $user, Group $group)
{
dd($group);
}
My question is how does the $group
model object gets constructed here from a raw route parameter string?
My guess is laravel's service container does the following magic (maybe sth like
- Injecting the Group model,
- then do sth like
Group::where('id', $group)->first()
but unsure about this.
CodePudding user response:
You guess right. There is a binding in the core service provider which retrieves model. The bound model is the same if you would call:
$temp = new Group
$model = Group::where($temp->getRouteKeyName(), request()->route('group'))->firstOrFail();
UPD. Actualy just found where it happens:
/**
* Retrieve the model for a bound value.
*
* @param \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Relations\Relation $query
* @param mixed $value
* @param string|null $field
* @return \Illuminate\Database\Eloquent\Relations\Relation
*/
public function resolveRouteBindingQuery($query, $value, $field = null)
{
return $query->where($field ?? $this->getRouteKeyName(), $value);
}