Jens Segers on

Laravel route model binding is awesome

If you haven't looked at Laravel's route model binding, you should definitely do it. Model binding allows you to inject model instances into your routes. This way, route parameters will automatically be converted to the model that matches the given id. Take the following route for example:

Route::get('profile/{user}', 'UserController@showProfile');

With model binding, Laravel will inject the user model, instead of the id from the URL. These bindings are defined like this:

Route::model('user', 'User');

You controller method will then look like this:

public function showProfile(User $user)
{
    return View::make('profile', ['user' => $user]);
}

Instead of:

public function showProfile($id)
{
    $user = User::find($id);

    return View::make('profile', ['user' => $user]);
}

Pretty cool right? It makes your controller code cleaner, and it will also automatically throw a 404 error if the matching model instance is not found in the database.

If you wish to use your own resolver, and/or do some additional security checks, you can define a custom binding:

Route::bind('user', function($value, $route)
{
    $user = User::where('name', $value)->firstOrFail();

    if ($user-> isSuperUser()) App::abort(403, 'Unauthorized action.');

    return $user;
});

I usually group all my bindings in app/bindings.php. To make sure this file gets loaded, add this to the bottom of app/start/global.php:

/*
|--------------------------------------------------------------------------
| Require Route Bindings File
|--------------------------------------------------------------------------
*/

require app_path().'/bindings.php';

You can read more about route model binding in the Laravel documentation: http://laravel.com/docs/routing#route-model-binding

Webmentions

Tweet about this blog post and you will appear below!