Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Laravel – how to retrieve url parameter in custom Request?

I need to make custom request and use its rules. Here’s what I have:

public function rules()
{
    return [
        'name' => 'required|min:2',
        'email' => 'required|email|unique:users,email,' . $id,
        'password' => 'nullable|min:4'
    ];
}

The problem is that I can’t get $id from url (example.com/users/20), I’ve tried this as some forums advised:

$this->id
$this->route('id')
$this->input('id')

But all of this returns null, how can I get id from url?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

When you are using resources, the route parameter will be named as the singular version of the resource name. Try this.

$this->route('user');

Bonus points

This sound like you are going down the path of doing something similar to this.

User::findOrFail($this->route('user'));

In the context of controllers this is an anti pattern, as Laravels container automatic can resolve these. This is called model binding, which will both handle the 404 case and fetching it from the database.

public function update(Request $request, User $user) {

}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading