Using Route/Model Binding In Laravel

Posted on · Tagged in

As I work more and more with Laravel, I keep running across some really cool time saving tricks. One of those time savers is route/model binding.

Let’s say that you have the following route setup.

<?php
Route::get('books/{book}', function($book) {
    return Book::find($book);
});

That’s pretty simple right? Basically you point your browser at /books and then pass a book id and then use the ‘Book’ model to fetch that book from the database. But say we already decided that the ‘books’ route should always be working with the book model and a book should be fetched automatically. Laravel gives us a method for explicitly binding the ‘Book’ model to our routes.

<?php
Route::model('book', 'Book');
 
Route::get('books/{book}', function($book) {
    return $book;
});

Now Laravel will take the id you pass to the route and automatically fetch it behind the scenes. What if we want to fetch a book by something other than it’s id? What if we want to access our books using a URI similar to /books/BookTitle? Instead of Route::model we can use Route::bind like this.

<?php
Route::bind('book', function($value, $route) {
    return Book::whereTitle($value);
});

This is a really good way to cut down on lines of code and at the same time keep it more readable.

Comments

comments powered by Disqus
Subscribe to my newsletter and get a free copy of my book, Aspect Oriented Programming in PHP.