3
votes

I have one form and it is in edit page, which has field name email. Now I don't want to check email validation, which is unique. I have already put validation in rules like 'email'=>'unique:users', which perfectly works on create page.So that validation I want to ignore on edit page. And I have to use FormRequest class like FormRequest $request in update function's argument, which defines rules array of form's fields validations.

public function rules()
    {
        $business = BusinessModel::all();

        return[
                'companyName' =>'required',
                'address1'    =>'required',
                'pinCode'     =>'required|numeric',
                'city'        =>'required',
                'email'       =>'required|email|unique:users'.$id,
                'phoneNumber' =>'required|numeric|unique:business|size:10',
                'website'     =>'required|url',
                'contactname' =>'required',
                'designation' =>'required',
                'emailaddress'=>'required|email|unique:business',
                'phno'        =>'required|numeric',
              ];
      }

How can we pass id to rules function in FormRequest class..because in this case..It'll show me error like, $id is undefined
'email' =>'required|email|unique:users'.$id, [error undefined variable id]

2

2 Answers

2
votes

just pass the primary key of the current record, validator will skip that row in table.

'email'=>'unique:users,email,'.$id,

in which,

email is the field name. $id is the variable in which primary key is stored.

0
votes

Because you're using the FormRequest class the $id variable isn't directly available to you.

However the same data will already be available to this class through either the form inputs or the route parameters depending on how you've structured things.

So if the route is something like myapp/user/234 then you can access the user id using $this->route('user')

This would make your rule look like:

   public function rules()
    {
        $business = BusinessModel::all();

        return[
                'companyName' =>'required',
                'address1'    =>'required',
                'pinCode'     =>'required|numeric',
                'city'        =>'required',
                'email'       =>'required|email|unique:users'.$this->route('user'),
                'phoneNumber' =>'required|numeric|unique:business|size:10',
                'website'     =>'required|url',
                'contactname' =>'required',
                'designation' =>'required',
                'emailaddress'=>'required|email|unique:business',
                'phno'        =>'required|numeric',
              ];
      }

Alternatively if the id is part of a form field rather than in the route you can access it using the request input method $this->input('id').

Full documentation on this can be found at: https://laravel.com/docs/5.6/requests#retrieving-input