Laravel 5 compatible and general way:
I had the same problem and it was solved in a general way. If you create an element, it uses the default rules; if you update an element, it will check your rules for :unique and automatically add an exception (if necessary).
Create a BaseModel class and let all your models inherit from it:
<?php namespace App; use Illuminate\Database\Eloquent\Model; class BaseModel extends Model { /** * The validation rules for this model * * @var array */ protected static $rules = []; /** * Return model validation rules * * @return array */ public static function getRules() { return static::$rules; } /** * Return model validation rules for an update * Add exception to :unique validations where necessary * That means: enforce unique if a unique field changed. * But relax unique if a unique field did not change * * @return array; */ public function getUpdateRules() { $updateRules = []; foreach(self::getRules() as $field => $rule) { $newRule = []; // Split rule up into parts $ruleParts = explode('|',$rule); // Check each part for unique foreach($ruleParts as $part) { if(strpos($part,'unique:') === 0) { // Check if field was unchanged if ( ! $this->isDirty($field)) { // Field did not change, make exception for this model $part = $part . ',' . $field . ',' . $this->getAttribute($field) . ',' . $field; } } // All other go directly back to the newRule Array $newRule[] = $part; } // Add newRule to updateRules $updateRules[$field] = join('|', $newRule); } return $updateRules; } }
Now you define your rules in your model, as you are used to:
protected static $rules = [ 'name' => 'required|alpha|unique:roles', 'displayName' => 'required|alpha_dash', 'permissions' => 'array', ];
And confirm them in your controller. If the model is not validated, it automatically redirects back to the form with the corresponding validation errors. If verification errors did not occur, it will continue to execute code after it.
public function postCreate(Request $request) { // Validate $this->validate($request, Role::getRules()); // Validation successful -> create role Role::create($request->all()); return redirect()->route('admin.role.index'); } public function postEdit(Request $request, Role $role) { // Validate $this->validate($request, $role->getUpdateRules()); // Validation successful -> update role $role->update($request->input()); return redirect()->route('admin.role.index'); }
What is this! :) Note that when creating, we call Role::getRules() , and when editing we call $role->getUpdateRules() .
cgross Jan 31 '15 at 17:38 2015-01-31 17:38
source share