User Route Model Binding

User model has different variable name that you can use to inject in your routes or controllers the model instance of user. Below you can find all available.

// User by ID for admin with global scope
$this->app->router->bind('user', function ($id) {
    return $this->app->make(User::class)->findOrFail($id);
});

// User by ID for admin without any global scope
$this->app->router->bind('userWithoutScopes', function ($id) {
    return $this->app->make(User::class)->withoutGlobalScopes()->findOrFail($id);
});

// User by username for frontend profile with global scope
$this->app->router->bind('username', function ($username) {
    return $this->app->make(User::class)->whereUsername($username)->firstOrFail();
});

// Only trashed user scope
$this->app->router->bind('onlyTrashedUser', function ($id) {
    return $this->app->make(User::class)->onlyTrashed()->withBanned()->findOrFail($id);
});

// With trashed user scope
$this->app->router->bind('withTrashedUser', function ($id) {
    return $this->app->make(User::class)->withTrashed()->findOrFail($id);
});

// Only banned user scope
$this->app->router->bind('onlyBannedUser', function ($id) {
    return $this->app->make(User::class)->onlyBanned()->findOrFail($id);
});

// With banned user scope
$this->app->router->bind('withBannedUser', function ($id) {
    return $this->app->make(User::class)->withBanned()->findOrFail($id);
});

// Without banned user scope
$this->app->router->bind('withoutBannedUser', function ($id) {
    return $this->app->make(User::class)->withoutBanned()->findOrFail($id);
});

In your routes you can see example of routes of admin how this are used, below is the code of routes of admin for user model:

Route::get('{userWithoutScopes}', 'UserController@show')->name('show');
Route::put('{user}/update-account', 'UserController@updateAccount')->name('update_account');
Route::delete('{withBannedUser}/trash', 'UserController@trash')->name('trash');
Route::delete('{onlyTrashedUser}/destroy', 'UserController@destroy')->name('destroy');
Route::patch('{onlyTrashedUser}/restore', 'UserController@restore')->name('restore');
Route::patch('{user}/confirm', 'UserController@confirm')->name('confirm');
Route::patch('{withoutBannedUser}/ban', 'UserController@ban')->name('ban');
Route::patch('{onlyBannedUser}/unban', 'UserController@unban')->name('unban');

This allow you for example to define an URL only for certain users. For example only banned users can be unbanned, or only trashed users can be restored or deleted.

This way it's also useful so that all business logic of users is centralized in single file and you don't need to retrieve user instance for each controller method.

Also code generator use the same way for resources.