DEV Community

Victor Basumatary
Victor Basumatary

Posted on

3 2

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.

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

Cloudinary image

Optimize, customize, deliver, manage and analyze your images.

Remove background in all your web images at the same time, use outpainting to expand images with matching content, remove objects via open-set object detection and fill, recolor, crop, resize... Discover these and hundreds more ways to manage your web images and videos on a scale.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay