DEV Community

Victor Basumatary
Victor Basumatary

Posted on

Laravel Route Parameters & Controller Actions

Laravel is nice. It'll automatically inject the models you need into your controller actions.

// app/Http/Controllers/FilmReviewController.php
class FilmReviewController extends Controller {
    public function edit(Request $request, FilmReview $filmReview)
    {
        //
    }
}
Enter fullscreen mode Exit fullscreen mode

What isn't nice though is that your controller action's parameter names must match the route parameter names. This might catch some of you by surprise. It sure did me.

Let's suppose I defined the following resource route:

// routes/web.php
Route::resource('reviews', 'FilmReviewController');
Enter fullscreen mode Exit fullscreen mode

This will create the following route for the edit action:

PUT /reviews/{review}
Enter fullscreen mode Exit fullscreen mode

I must now update my controller like so:

// Notice I changed $filmReview to $review
public function edit(Request $request, FilmReview $review)
{
    //
}
Enter fullscreen mode Exit fullscreen mode

If the route parameter name and the parameter name of your controller action don't match, the model won't be fetched from your db. So calls like $review->id will always return null.

Top comments (0)