phplaravellaravel-5.7

Laravel: Get ID on a FormRequest Rule


I created a rule to check if email already exist only if the field was changed.

$rules = [
    'user-name'      => 'required',
    'user-email'     => [
        'required',
        'email',
        Rule::unique('users', 'email')->ignore(ID)
    ],
];

But I need to inform the user ID. How can I grab this information?

Route::resource('users', 'UsersController')->middleware('permission:create users');

Solution

  • In your Form request you have access to the authenticated user, so you can use:

    $this->user()->id
    

    --- Edit

    getting the id from the url:

    request()->route('id')
    

    -- Second try

    $this->route('user')
    

    Or print out using php artisan route:list and whatever is used on the url as {user} or {id} that's what you need to use.