• Home
  • blog
  • Laravel Quick Tip: Model Route Binding

Laravel Quick Tip: Model Route Binding

One of the great things that Laravel provides is the easy to use routing component. It offers simple URLs, parameters, grouping, naming and event guarding route groups, to name a few of the different options.

Laravel logo

Let’s pretend we have a list of categories in a database, and the admin can manage categories from the back end. Here’s how your routes file should look like.

Route::group(['namespace' => 'Admin', 'prefix' => 'admin', 'middleware' => 'admin'], function () {
    Route::resource('categories', 'CategoriesController');

Inside your CategoriesController class, you’ll have the seven resource methods. Inside the edit action, we should check if the category being edited exists in the database, otherwise we redirect back with an error message.

public function edit($id)
    $category = Category::find($id);
    if (!$category) {
        return redirect()->route('admin.categories.index')->withErrors([trans('errors.category_not_found')]);

    // ...

Model Binding

This is the usual way of doing it, but Laravel also has a nicer way of optimizing this repetitive task called route model binding. You basically type hint the model name instead of the ID parameter.

Continue reading %Laravel Quick Tip: Model Route Binding%