Passing route parameters to the route() helper in laravel

When your route has parameters (e.g. users/{id}), you need to define those parameters when you’re using the route() helper to generate a link to the route.

There are a few different ways to pass these parameters. Let’s imagine a route defined as users/{userId}/comments/{commentId}. If the user ID is 1 and the comment ID is 2, let’s look at a few options we have available to us.

OPTION 1.

route('users.comments.show', [1, 2])
// http://myapp.com/users/1/comments/2

OPTION 2.

route('users.comments.show', ['userId' => 1, 'commentId' => 2])
// http://myapp.com/users/1/comments/2

OPTION 3.

route('users.comments.show', ['commentId' => 2, 'userId' => 1])
// http://myapp.com/users/1/comments/2

OPTION 4.

route('users.comments.show', ['userId' => 1, 'commentId' => 2, 'opt' => 'a'])
// http://myapp.com/users/1/comments/2?opt=a

As you can see, non-keyed array values are assigned in order; keyed array values are matched with the route parameters matching their key; and anything left over is added as a query parameter.

Recommended :  How to Collect and Handle User Data in laravel

About the author

Deven Rathore

I'm Deven Rathore, a multidisciplinary & self-taught designer with 3 years of experience. I'm passionate about technology, music, coffee, traveling and everything visually stimulating. Constantly learning and experiencing new things.

Pin It on Pinterest

Shares