Home > Software design >  Laravel: Validation Rule Ignore submitted ID in FormRequest class
Laravel: Validation Rule Ignore submitted ID in FormRequest class

Time:10-10

I would like to ignore one of the inputs inside a FormRequest class. Previously, I've already done it on my previous Laravel project using the exact same code (The previous Laravel project was Laravel Version 7). Here is the code of my ignore validation:

class UserRequest extends FormRequest
{
    protected $user;

    public function __construct(Request $request)
    {
        $this->user = $request->route()->client;
    }

    public function rules()
    {
        return [
            'email' => ['nullable', 'string', 'email', 'max:100', 'unique:users,email,'.$this->user.',user_id'],
        ];
    }

The line code "$request->route()->client" is to get the submitted form request data (client is one of the route inside the web.php file). But when I try this code inside the current project (Current project is Laravel 8). The results was the email was not ignored.

I guess there are something new in Laravel 8 about FormRequest? How can I solve this?

UPDATE

Here is my route (web.php) code:

Route::middleware('auth')->group(function () {
    Route::resource('users', UserController::class);

And here is my users table structure:

enter image description here

I used the resource Controller so the route is simple.

CodePudding user response:

try following way

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

class UserRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array<string, mixed>
     */
    public function rules()
    {

        return [
            'email' => [
                'nullable', 'string', 'email', 'max:100',
                Rule::unique('users','email')->ignore($this->route()->client,'user_id'),
            ],
        ];
    }
}

and ignore method accept two params

ignore($id, $idColumn = null)

for the second column default, it treats as the id column as the primary key.if not then we should specify the column name.

so there is no need to use a constructor and all

  • Related