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.

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

Originally published at