loading...

Laravel Route Parameters & Controller Actions

vlence profile image Victor Basumatary ・1 min read

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)
    {
        //
    }
}

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');

This will create the following route for the edit action:

PUT /reviews/{review}

I must now update my controller like so:

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

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.

Posted on by:

vlence profile

Victor Basumatary

@vlence

Serverless? DevOps? Yes please!

Discussion

pic
Editor guide