I have a Laravel User model which has a unique validation rule on username and email. In my Repository, when I update the model, I revalidate the fields, so as to not have a problem with required rule validation:
public function update($id, $data) {
$user = $this->findById($id);
$user->fill($data);
$this->validate($user->toArray());
$user->save();
return $user;
}
This fails in testing with:
ValidationException: {"username":["The username has already been
taken."],"email":["The email has already been taken."]}
Is there a way of fixing this elegantly?
Append the id of the instance currently being updated to the validator.
Pass the id of your instance to ignore the unique validator.
In the validator, use a parameter to detect if you are updating or creating the resource.
If updating, force the unique rule to ignore a given id:
//rules
'email' => 'unique:users,email_address,' . $userId,
If creating, proceed as usual:
//rules
'email' => 'unique:users,email_address',
Another elegant way...
In your model, create a static function:
public static function rules ($id=0, $merge=[]) {
return array_merge(
[
'username' => 'required|min:3|max:12|unique:users,username' . ($id ? ",$id" : ''),
'email' => 'required|email|unique:member'. ($id ? ",id,$id" : ''),
'firstname' => 'required|min:2',
'lastname' => 'required|min:2',
...
],
$merge);
}
Validation on create:
$validator = Validator::make($input, User::rules());
Validation on update:
$validator = Validator::make($input, User::rules($id));
Validation on update, with some additional rules:
$extend_rules = [
'password' => 'required|min:6|same:password_again',
'password_again' => 'required'
];
$validator = Validator::make($input, User::rules($id, $extend_rules));
Nice.
Working within my question:
public function update($id, $data) {
$user = $this->findById($id);
$user->fill($data);
$this->validate($user->toArray(), $id);
$user->save();
return $user;
}
public function validate($data, $id=null) {
$rules = User::$rules;
if ($id !== null) {
$rules['username'] .= ",$id";
$rules['email'] .= ",$id";
}
$validation = Validator::make($data, $rules);
if ($validation->fails()) {
throw new ValidationException($validation);
}
return true;
}
is what I did, based on the accepted answer above.
EDIT: With Form Requests, everything is made simpler:
<?php namespace App\Http\Requests;
class UpdateUserRequest extends Request
{
/**
* 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
*/
public function rules()
{
return [
'name' => 'required|unique:users,username,'.$this->id,
'email' => 'required|unique:users,email,'.$this->id,
];
}
}
You just need to pass the UpdateUserRequest to your update method, and be sure to POST the model id.
Unique Validation With Different Column ID In Laravel
'UserEmail'=>"required|email|unique:users,UserEmail,$userID,UserID"
or what you could do in your Form Request is (for Laravel 5.3+)
public function rules()
{
return [
'email' => 'required|email|unique:users,email,'. $this->user
//here user is users/{user} from resource's route url
];
}
i've done it in Laravel 5.6 and it worked.
'email' => [
'required',
Rule::exists('staff')->where(function ($query) {
$query->where('account_id', 1);
}),
],
'email' => [
'required',
Rule::unique('users')->ignore($user->id)->where(function ($query) {
$query->where('account_id', 1);
})
],
Laravel 5 compatible and generic way:
I just had the same problem and solved it in a generic way. If you create an item it uses the default rules, if you update an item it will check your rules for :unique and insert an exclude automatically (if needed).
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;
}
}
You now define your rules in your model like you are used to:
protected static $rules = [
'name' => 'required|alpha|unique:roles',
'displayName' => 'required|alpha_dash',
'permissions' => 'array',
];
And validate them in your Controller. If the model does not validate, it will automatically redirect back to the form with the corresponding validation errors. If no validation errors occurred it will continue to execute the 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');
}
That's it! :) Note that on creation we call Role::getRules() and on edit we call $role->getUpdateRules().
I have BaseModel class, so I needed something more generic.
//app/BaseModel.php
public function rules()
{
return $rules = [];
}
public function isValid($id = '')
{
$validation = Validator::make($this->attributes, $this->rules($id));
if($validation->passes()) return true;
$this->errors = $validation->messages();
return false;
}
In user class let's suppose I need only email and name to be validated:
//app/User.php
//User extends BaseModel
public function rules($id = '')
{
$rules = [
'name' => 'required|min:3',
'email' => 'required|email|unique:users,email',
'password' => 'required|alpha_num|between:6,12',
'password_confirmation' => 'same:password|required|alpha_num|between:6,12',
];
if(!empty($id))
{
$rules['email'].= ",$id";
unset($rules['password']);
unset($rules['password_confirmation']);
}
return $rules;
}
I tested this with phpunit and works fine.
//tests/models/UserTest.php
public function testUpdateExistingUser()
{
$user = User::find(1);
$result = $user->id;
$this->assertEquals(true, $result);
$user->name = 'test update';
$user->email = 'ddd#test.si';
$user->save();
$this->assertTrue($user->isValid($user->id), 'Expected to pass');
}
I hope will help someone, even if for getting a better idea. Thanks for sharing yours as well.
(tested on Laravel 5.0)
A simple example for roles update
// model/User.php
class User extends Eloquent
{
public static function rolesUpdate($id)
{
return array(
'username' => 'required|alpha_dash|unique:users,username,' . $id,
'email' => 'required|email|unique:users,email,'. $id,
'password' => 'between:4,11',
);
}
}
.
// controllers/UsersControllers.php
class UsersController extends Controller
{
public function update($id)
{
$user = User::find($id);
$validation = Validator::make($input, User::rolesUpdate($user->id));
if ($validation->passes())
{
$user->update($input);
return Redirect::route('admin.user.show', $id);
}
return Redirect::route('admin.user.edit', $id)->withInput()->withErrors($validation);
}
}
If you have another column which is being used as foreign key or index then you have to specify that as well in the rule like this.
'phone' => [
"required",
"phone",
Rule::unique('shops')->ignore($shopId, 'id')->where(function ($query) {
$query->where('user_id', Auth::id());
}),
],
I am calling different validation classes for Store and Update. In my case I don't want to update every fields, so I have baseRules for common fields for Create and Edit. Add extra validation classes for each. I hope my example is helpful. I am using Laravel 4.
Model:
public static $baseRules = array(
'first_name' => 'required',
'last_name' => 'required',
'description' => 'required',
'description2' => 'required',
'phone' => 'required | numeric',
'video_link' => 'required | url',
'video_title' => 'required | max:87',
'video_description' => 'required',
'sex' => 'in:M,F,B',
'title' => 'required'
);
public static function validate($data)
{
$createRule = static::$baseRules;
$createRule['email'] = 'required | email | unique:musicians';
$createRule['band'] = 'required | unique:musicians';
$createRule['style'] = 'required';
$createRule['instrument'] = 'required';
$createRule['myFile'] = 'required | image';
return Validator::make($data, $createRule);
}
public static function validateUpdate($data, $id)
{
$updateRule = static::$baseRules;
$updateRule['email'] = 'required | email | unique:musicians,email,' . $id;
$updateRule['band'] = 'required | unique:musicians,band,' . $id;
return Validator::make($data, $updateRule);
}
Controller:
Store method:
public function store()
{
$myInput = Input::all();
$validation = Musician::validate($myInput);
if($validation->fails())
{
$key = "errorMusician";
return Redirect::to('musician/create')
->withErrors($validation, 'musicain')
->withInput();
}
}
Update method:
public function update($id)
{
$myInput = Input::all();
$validation = Musician::validateUpdate($myInput, $id);
if($validation->fails())
{
$key = "error";
$message = $validation->messages();
return Redirect::to('musician/' . $id)
->withErrors($validation, 'musicain')
->withInput();
}
}
public static function custom_validation()
{
$rules = array('title' => 'required ','description' => 'required','status' => 'required',);
$messages = array('title.required' => 'The Title must be required','status.required' => 'The Status must be required','description.required' => 'The Description must be required',);
$validation = Validator::make(Input::all(), $rules, $messages);
return $validation;
}
I had the same problem.
What I've done: add in my view hidden field with id of a model and in validator check the unique, only if I've get some id from view.
$this->validate(
$request,
[
'index' => implode('|', ['required', $request->input('id') ? '' : 'unique:members']),
'name' => 'required',
'surname' => 'required',
]
);
You can trying code bellow
return [
'email' => 'required|email|max:255|unique:users,email,' .$this->get('id'),
'username' => 'required|alpha_dash|max:50|unique:users,username,'.$this->get('id'),
'password' => 'required|min:6',
'confirm-password' => 'required|same:password',
];
Laravel 5.8 simple and easy
you can do this all in a form request with quite nicely. . .
first make a field by which you can pass the id (invisible) in the normal edit form. i.e.,
<div class="form-group d-none">
<input class="form-control" name="id" type="text" value="{{ $example->id }}" >
</div>
...
Then be sure to add the Rule class to your form request like so:
use Illuminate\Validation\Rule;
... Add the Unique rule ignoring the current id like so:
public function rules()
{
return [
'example_field_1' => ['required', Rule::unique('example_table')->ignore($this->id)],
'example_field_2' => 'required',
];
... Finally type hint the form request in the update method the same as you would the store method, like so:
public function update(ExampleValidation $request, Examle $example)
{
$example->example_field_1 = $request->example_field_1;
...
$example->save();
$message = "The aircraft was successully updated";
return back()->with('status', $message);
}
This way you won't repeat code unnecessarily :-)
public function rules()
{
if ($this->method() == 'PUT') {
$post_id = $this->segment(3);
$rules = [
'post_title' => 'required|unique:posts,post_title,' . $post_id
];
} else {
$rules = [
'post_title' => 'required|unique:posts,post_title'
];
}
return $rules;
}
For a custom FormRequest and Laravel 5.7+ you can get the id of your updated model like this:
public function rules()
{
return [
'name' => 'required|min:5|max:255|unique:schools,name,'.\Request::instance()->id
];
}
For anyone using a Form request
In my case i tried all of the following none of them worked:
$this->id, $this->user->id, $this->user.
It was because i could not access the model $id nor the $id directly.
So i got the $id from a query using the same unique field i am trying to validate:
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
$id = YourModel::where('unique_field',$this->request->get('unique_field'))->value('id');
return [
'unique_field' => ['rule1','rule2',Rule::unique('yourTable')->ignore($id)],
];
}
It will work 100%
I have both case implement like One case is same form field in database table products and other is products_name is form field and in table, it's name is name, how we can validate and ignore that id while updating. I have encrypted that so i'm decrypted id, if you are encrypt then you will decrypt otherwise pass it as it's coming from the form.
$request->validate([
'product_code' => 'required|unique:products,product_code,'.decrypt($request->hiddenProductId),
'products_name' => 'required|unique:products,name,'.decrypt($request->hiddenProductId),
]);
there is detailed and straightforward answer to this question, I was looking for too
https://laravel.com/docs/9.x/validation#rule-unique
User model is returning id=null, while debug I found out the the reason behind this issue is that in my User model I override the $primary_key with a custom one
User Model
class User extends Authenticatable
{
use Notifiable;
// Set the primary key to the generated version instead of the regular ID
protected $primaryKey = 'user_code';
// Set the key type
protected $keyType = 'string';
// Diable the auto-increment option
public $incrementing = false;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'user_code',
'fname',
'mname',
'lname',
'email',
'dob',
'age',
'gender',
'insurance_number',
'ssn',
'avatar',
'is_active',
'userable_id',
'userable_type',
];
}
I have the following code that generate a new user_code that uses the id
$user = new User;
$user = $user->create([
'fname' => $request->fname,
'lname' => $request->lname,
'email' => $request->email,
]);
// Save the user in the DB
// Generate a usercode for the newely created user
$userCode = "ur" . date('y') . date('m') . $user->id;
Users Migration:
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('user_code')->unique()->nullable();
$table->string('fname')->default('tbd');
$table->string('mname')->default('tbd');
$table->string('lname')->default('tbd');
$table->string('email')->unique()->nullable();
$table->date('dob')->default('1000-01-01');
$table->integer('age')->default(0);
$table->string('gender')->default('tbd');
$table->integer('insurance_number')->default(0);
$table->integer('ssn')->default(0);
$table->string('avatar')->default('tbd');
$table->boolean('is_active')->default(false);
$table->string('userable_code')->default('tbd');
$table->string('userable_type')->default('tbd');
$table->timestamp('email_verified_at')->nullable();
$table->rememberToken();
$table->timestamps();
});
$user->id is returning null, why such behavior is happening?
You've set $user as a new model instance:
$user = new User;
But then you're trying to create a new user from that instance, that won't work:
$user = $user->create([ ...
Since that doesn't work, you're not really saving anything to the DB, and you won't get an ID.
The second part of your problem is (as #TimLewis pointed out in the comments) that you are trying to create and save a model with a blank primary key (user_code). That won't work, so you'll need to work out what the ID is before trying to save it.
// Remove this line:
// $user = new User;
// Find the current highest ID:
$last = User::max('id');
// Your new user will have this ID
$newID = $last->id + 1;
// And just use the normal way to create and save a model:
$user = User::create([
'userCode' => "ur" . date('y') . date('m') . $newID,
'fname' => $request->fname,
'lname' => $request->lname,
'email' => $request->email,
]);
I may not know what you are trying to achieve here, but I'm just assuming that this is a very special use case.
Try this:
// Notice how we are using the User as a class, not instantiating it.
$user = User::create([
'fname' => $request->fname,
'lname' => $request->lname,
'email' => $request->email,
]);
// Save the user in the DB
// Generate a usercode for the newely created user
$userCode = "ur" . date('y') . date('m') . $user->id;
This assumes that your id column in your database table is still INCREMENTS and PRIMARY KEY
I'm creating an Add-User function in my website (Laravel 5.1), in which an admin account can create an account using an email, and the password will be sent to that email. The form in the Add-User view asks for the name, email, permission level, and description.
The create function supposed to accept a request from that wiew, generate a password, add the password and the creator's ID into the request, create a DB entry based on the request, then send an email to that address. I'm currently stuck at creating the DB based on the request. Here is my function :
public function create(Request $request)
{
//generate password
$pass = str_random(10);
$passcrypt = bcrypt($pass);
$email = $request->input('email');
//change the fillable in the model
$user = new User;
$user->changeFillableMode("CREATE");
//validation
$this->validate($request,['fullname'=>'required',
'email'=>'required|email',
'permission_id'=>'required']);
//adding new items to request array
$input = $request->all();
$input = array_add($input,'created_by_user_id',Auth::user()->user_id);
$input = array_add($input,'password',$passcrypt);
$user->create($input);
//send mail
$data['email'] = $request->input('email');
$data['pass'] = $pass;
Mail::queue('mail.mailbodycreate', $data, function($message) use ($email)
{
$message->to($email)->subject('Account info');
});
}
The $input already shows that the password and creator Id are already in the array, but I keep getting error that it's not in the array (since password is not nullable in my migration). can anyone help?
update : I add dd($input); after the last array_add. this is the result
array:7 [
"_token" => "9VowN9ICgkAb9cegbbQzhFtfIhmQr0DqlGj724bN"
"fullname" => "Aldi"
"email" => "aldi#gmail.com"
"permission_id" => "1"
"description" => "testing add user"
"created_by_user_id" => 4
"password" => "$2y$10$Dc4TZqMYE1kyPc7wFHBT1.8KUzk35QqV32wKegstjMFHnD/rhjsw6"
]
update 2 : here is the model for the User table :
protected $table = 'msuser';
protected $primaryKey = 'user_id';
protected $fillable = ['fullname', 'email', 'description','permission_id'];
protected $hidden = ['password', 'remember_token'];
protected $dates = ['deleted_at'];
public function changeFillableMode($mode){
switch($mode){
case "CREATE" :
$this->fillable = ['fullname', 'email', 'password', 'description','permission_id','created_by_user_id','has_change_password'];
break;
}
}
the changeFillableMode is used to change the content of $fillable in the controller function.
I prefer to add key-value pairs in PHP this way:
//adding new items to request array
$input = $request->all();
$input['created_by_user_id'] = Auth::user()->user_id;
$input['password'] = $passcrypt;
ensure that protected $fillable contains all required keys before create
use constants for switch:
const CREATE = 'create';
public function changeFillableMode($mode){
switch($mode){
case self::CREATE:
$this->fillable = ['fullname', 'email', 'password', 'description','permission_id','created_by_user_id','has_change_password'];
break;
}
}
and call it:
$user->changeFillableMode(User::CREATE);
I'm following this Laravel login/register tutorial on YouTube and I ran into a problem.
It seems I cannot insert the data from the $user object into my database.
Everything I have so far works perfectly fine until I reach the $user->save() method.
The following is my AccountController.php. You'll notice that I'm using print_r to try and debug the process. The first print_r gets printed to my page, but the second never does: Laravel just stops and outputs a cryptic Whoops, looks like something went wrong. warning.
class AccountController extends BaseController {
public function getCreate()
{
return View::make('account.create');
}
public function postCreate()
{
$validator = Validator::make(Input::all(), array(
'email' => 'required|max:64|min:3|email|unique:users',
'name' => 'required|max:64|min:3',
'password' => 'required|max:64|min:6'
));
if ($validator->fails())
{
// Return to form page with proper error messages
return Redirect::route('account-create')
->withErrors($validator)
->withInput();
}
else
{
// Create an acount
$email = Input::get('email');
$name = Input::get('name');
$password = Input::get('password');
// Activation code
$code = str_random(64);
$user = User::create(array(
'active' => 0,
'email' => $email,
'username' => $name,
'password' => Hash::make($password),
'code' => $code
));
if ($user)
{
// Send the activation link
Mail::send('emails.auth.activate', array(
'link' => URL::route('account-activate', $code),
'name' => $name
), function($message) use($user) {
$message
->to($user->email, $user->username)
->subject('Jasl | Activate your new account');
});
return Redirect::route('home')
->with('success', 'One more step! You\'ll get an email from us soon. Please follow the activation link to activate your account.');
}
}
}
public function getActivate($code)
{
// Find user whose code corresponds to the one we've previously sent through email
$user = User::where('code', '=', $code)->where('active', '=', 0);
if ($user->count())
{
$user = $user->first();
$user->active = 1;
$user->code = '';
echo '<pre>', print_r($user), '<pre>';
if ($user->save())
{
echo '-----------------------';
echo '<pre>', print_r($user), '<pre>';
}
}
}
}
I've googled a bit and found out that I should create a $fillable array in my User class, so I did it:
use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends Eloquent implements UserInterface, RemindableInterface {
protected $fillable = array('active', 'name', 'email', 'password', 'password_temp', 'code', 'salt', 'created_at', 'updated_at', 'pref_weight', 'pref_units', 'pref_time', 'pref_ener');
use UserTrait,
RemindableTrait;
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'users';
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = array('password', 'remember_token');
}
Those are actually all the elements that my users table has.
This did not solve the problem.
What am I missing? Why isn't $user->save() working properly?
I got it.
My problem was that I created the id column of my users table with a custom name, user_id, instead of simply id. Apparently Laravel does not like this at all. The debugger pointed me to:
C:\xampp\htdocs\laravel\vendor\laravel\framework\src\Illuminate\Database\Connection.php
with the error:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'id' in 'where clause' (SQL: update users set active = 1, code = , updated_at = 2015-01-20 21:28:14 where id is null)
I didn't know you shouldn't customize id columns. Renaming it solved the problem entirely and the database now updates correctly.
Thanks #patricus for the useful debugging tip, that's what allowed me to track this error down.