Home > Software engineering >  Laravel - how to retrieve url parameter in custom Request?
Laravel - how to retrieve url parameter in custom Request?

Time:12-02

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?

CodePudding user response:

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

}
  • Related