validationlaravel-5url-parameters

How to get and pass URL parameters to classes in Laravel 5.1?


In Laravel 5.1's Routing documentation, it seems it doesn't tell how to get and pass URL parameters to classes. So how should we get route parameters from URLs?

For example, using RESTful Resource Controller to update a user's profile, your app PATCHes (POST actually) to:

/profile/10

So when inside the rules() method in UpdateUserRequest, how do you get the id 10 from the URL to validate user's email as unique from other users like this?

public fnction rules()
{
    return [ 'email' => 'uniqie:users,email,'.$id ]
}

If i dd(Request::all()), it does not contain 'id' = '10'. PLease help. Thank you!

Updates

In the Form Request Validation doc, it said that Laravel grants you to access route/URL parameters with:

$this->route('id');

But it only works on non-resource routes like:

Route::post('users/{id}', 'UsersController@store');

It doesn't work with:

Route::resource('users', 'UserController');

So how do you get and pass route parameters from resource routes?


Solution

  • Return id to UpdateUserRequest:

    $id = $this->route('users');
    

    because Route:resource will give you /users/{users} instead of /users/{id}.

    you can use this command via command line :

    php artisan route:list
    

    to help you get list all of the route.