Custom route bindings

Did you know you can define custom route bindings in Laravel?

In this example, I need to resolve a portfolio by slug. But the slug is not unique, because multiple users can have a portfolio named 'Foo'

So I define how Laravel should resolve them from a route parameter

1class RouteServiceProvider extends ServiceProvider
2{
3 public const HOME = '/dashboard';
4 
5 public function boot()
6 {
7 Route::bind('portfolio', function (string $slug) {
8 return Portfolio::query()
9 ->whereBelongsto(request()->user())
10 ->whereSlug($slug)
11 ->firstOrFail();
12 });
13 }
14}
1Route::get('portfolios/{portfolio}', function (Portfolio $portfolio) {
2 /*
3 * The $portfolio will be the result of the query defined in the RouteServiceProvider
4 */
5})

Tip given by @mmartin_joo

Like our articles?

Become a Premium Member for $129/year or $29/month
What else you will get:
  • 22 courses (477 lessons, total 38 h 20 min)
  • 2 long-form tutorials (one new every week)
  • access to project repositories
  • access to private Discord