php - Laravel - Avoid validation error for unique rule when updating -


i'm using laravel 5.3's validation follows:

in model:

public static $validation = [     'name' => 'required',     'username' => 'required|alpha|unique:companies',     'email' => 'required|email|unique:companies', ]; 

in controller, post same companycontroller@datapost method when creating new item or when editing one:

public function datapost(request $request) {      // first validation     $this->validate($request, company::$validation);      $id = $request->id;      if ($id > 0) {         // edit!         $company = company::find($id);         $company->update($request->all());         $company->save();          session::flash('messageclass', 'success');         session::flash('message', trans('companies.editedsuccessfully'));      } else {         // create         $company = new company($request->all());         $company->save();          session::flash('messageclass', 'success');         session::flash('message', trans('companies.createdsuccessfully'));     }      return redirect()->route('companyindex'); } 

the unique validation works ok when create new item, causes error (as in flags username existing) when editing item.

any idea how avoid this? in edit i'd still want ensure data unique if it's changed, if value same before ignore validation.

i know manually, wonder if there built-in way avoid this.

thanks!

i think can try this:

public static $validation = [     'name' => 'required',     'email'     => auth::check()                 ? 'required|email|unique:companies,email,'.auth::id()                 : 'required|email|unique:companies,email',     'username'  => auth::check()                 ? 'required|alpha|unique:companies,username,'.auth::id()                 : 'required|alpha|unique:companies,username', ]; 

hope work !!!


Comments

Popular posts from this blog

php - Vagrant up error - Uncaught Reflection Exception: Class DOMDocument does not exist -

vue.js - Create hooks for automated testing -

Add new key value to json node in java -