How to add unique validation on combination of firstname and lastname in laravel5? - laravel-5

I need to validate user table in which not repeated combination of (firstname and lastname). for example:- firstname=dc lastname=patel already exist in table. i need to prevent same entry next time.

Finally I have perfect solution for this.
$validationRule = ['first_name' => 'required','last_name'=>'required'];
$validationMsg = ['first_name.required' => 'First Name is required', 'last_name.required' => 'Last Name is required'];
$validation = Validator::make(['first_name' => $firstName, 'last_name' => $lastName], $validationRule, $validationMsg);
$validation->after(function ($validation) use ($firstName, $lastName) {
$checkName = User::where('first_name', $firstName)->where('last_name', $lastName)->get();
if (count($checkName) > 0) {
$validation->errors()->add('first_name', 'User already exists, please enter another user.');
}
});
if ($validation->fails()) {
foreach ($validation->errors()->all() as $error) {
$message = $error;
}
return response(\Helpers::makeAjaxResponse(false, $message));
} else {
//Save record code here
}

You can use something simular to composite UNIQUE key in table if database provide this possibility.
http://dev.mysql.com/doc/refman/5.7/en/multiple-column-indexes.html

with using laravel unique validation rule
how can you allow users with same lastname but not firstname for registeration?
unique.firstname

First check records count with the given firstname and lastname.
If the count is '0' save the record or else show message.
Here is some code hint
$users = DB::table('users')
->where(['firstname' => 'dc', 'lastname' => 'patel'])
->count();
if($users === 0) {
// save the record.
} else {
// Show message
}

Since Laravel 5.5 you can use elegant Rule class like:
use Illuminate\Validation\Rule;
// ...
$firstNameUniqueRule = Rule::unique('users')->where('last_name', request()->get('last_name', ''));
$rules = [
'first_name' => ['required', $firstNameUniqueRule],
'last_name' => 'required',
];

Related

Laravel avoid duplication between existing data and new inputs

I have an edit form where it shows users, sub-users and I need to make my update method the way that it can update existed sub-users as well as add new ones.
Logic
User can have a maximum of 5 sub-users
Let's assume my user already have 2 sub-users s/he can add up to 3 more
I want to be able to update those 2 that are existed already
I want to be able to add those 3 new sub-users
Code
Here is what I have currently. Code is commented for better understanding
public function subUsersUpdate(Request $request, $id) {
$will = Will::where('id', $id)->where('user_id', Auth::id())->first();
// main user
$user = User::where('id', $will->user_id)->first();
// making custom emails for new users like (admin1#example.com)
// admin is email name of main user, originally (admin#gmail.com)
// 1~5 are added to names (separate those 5 sub-users)
// example.com is website domain
$userMail = substr($user->email, 0, strpos($user->email, '#'));
$websiteName = env('DOMAIN_NAME');
// here is what I get from edit form including 2 existed sub-users and 3 new sub-users
foreach($request->input('subs') as $index => $sub) {
// trying to separate existed sub-users from new ones
$existedUser = User::where('name', $sub)->where('user_id', $user->id)->first();
if($existedUser) {
// if already existed just update the name
$existedUser->update(['name' => $sub]);
} else {
// if new add them as new sub-user
$num = $index+1;
$password = str_random(15);
User::create([
'name' => $sub,
'email' => $userMail . $num ."#" . $websiteName,
'password' => Hash::make($password),
'user_id' => $user->id,
]);
}
}
return redirect()->back();
}
Error
SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'admin4#example.com' for key 'users_email_unique'
It appears that my code works in order to separate old and new sub-users but the problem is it makes the same email for new-users as old ones based on $num provided in my foreach. I need somehow avoid that duplication.
Any suggestion?
Update
What I did
I've added hidden input in my form which has sub-user email as value (if user existed) and if user is newly added it is null.
Then I merged those emails array and names array into one
Finally I've validate if the email field is null or not in order to update or create new sub-user.
Issue
Issue is name of all sub-users will be same as last input (sub-user 5), regardless of user being newly created or updated all 5 get same name!
public function subUsersUpdate(Request $request, $id) {
$will = Will::where('id', $id)->where('user_id', Auth::id())->first();
$user = User::where('id', $will->user_id)->first();
$userMail = substr($user->email, 0, strpos($user->email, '#'));
$websiteName = env('DOMAIN_NAME');
//Changed part
$mails = $request->input('mails');
$names = $request->input('subs');
// created array of data
$finalInputs = [];
foreach($mails as $index => $mmm) {
foreach($names as $index2 => $nnn) {
$finalInputs[$index] = ['email' => $mmm, 'name' => $nnn];
}
}
foreach($finalInputs as $index => $sub) {
if(!empty($sub['email'])) {
$existedUser = User::where('email', $sub['email'])->where('user_id', $user->id)->first();
$existedUser->update(['name' => $sub['name']]);
// $userMail2 = substr($sub['email'], 0, strpos($sub['email'], '#'));
} else {
if($sub['name'] != null) {
$num = $index+1;
$password = str_random(15);
User::create([
'name' => $sub['name'],
'email' => $userMail . $num ."#" . $websiteName,
'password' => Hash::make($password),
'user_id' => $user->id,
]);
}
}
}
// end of changed parts
}
Using updateOrCreate()
updateOrCreate() can handle conditional updating or creating of records for you.
This could be what you are asking, hope you get the idea:
foreach($finalInputs as $index => $sub) {
$pwHash = Hash::make( str_random(15) );
$num = $index+1;
$search = [
'user_id' => $user->id,
'email' => $userMail . $num ."#" . $websiteName,
];
$update = [
'name' => $sub['name'],
];
// Only add 'password' for new users
if (empty($sub['email']))) {
$update['password'] = $pwHash;
}
User::updateOrCreate(
$search,
$update
);
}
This will update or create users with the given email address and user-id and create if they don't exist. I don't know how your form works in detail, but I think you can adjust to your exact use-case.

Avoid duplication in doctor_id field with where clause in laravel 5.4

this is my doctors id
this is my user id
I can't insert anything when I put unique in the validation of doctor_id. When there's no unique it works fine.
I want to avoid duplicate doctor_id where auth::id == 1. Any advice is appreciated.
public function store(Request $request, $id)
{
$auth = Auth::id();
$constraints = [
'doctor_id' => 'required|unique',
'day1' => 'required|max:20',
'day2'=> 'required|max:60',
'day3' => 'required|max:60'
];
$input = [
'users_id' => $auth,
'doctor_id' => $id,
'day1' => $request['day1'],
'day2' => $request['day2'],
'day3' => $request['day3'],
'day4' => $request['day4'],
...
'day27' => $request['day27'],
'status' => '1'
];
$this->validate($request, $constraints);
Itinerary::create($input);
$added = array('added'=> 'Added Doctor to Itinerary Successful!!');
return redirect()->back()->with($added);
Have you tried this? (assuming your table is named itineraries):
'doctor_id' => 'unique:itineraries'
According to Laravel Doc, you should add the table name, and column name if possible:
unique:table,column,except,idColumn

How to exclude a perticular field from unique validation in edit mode in cakephp3.0 validation

I want to validate a field called survey_id which is an input from user for uniqueness. It is working properly and giving the correct response when adding the new record, but when I tried to edit this record it is giving an error [unique] => Provided value already exist. So what I want is to exclude the survey_id of the current record from uniqueness check and if user input some other value for survey_id it should check for uniqueness search.
Currently I am using the CakePHP 3.0 validation with on create validation. Here is the validation rule that I am using:
validator
->requirePresence('survey_id', __('msg_required'))
->notEmpty('survey_id', __('msg_required'))
->maxlength('survey_id', 32, __('msg_maxlength'))
->add('survey_id', 'unique', ['rule' => ['validateUnique',['id']], 'provider' => 'table', 'message' => 'Provided value already exist', 'on'=>'create']);
return $validator;
Is there anything wrong with this code?
Thanks in advance.
`
It will work with this validation rule
$validator
->requirePresence('survey_id', __('msg_required'))
->notEmpty('survey_id', __('msg_required'))
->maxlength('survey_id', 32, __('msg_maxlength'))
->alphaNumeric('survey_id', __('msg_surveyid_format'))
->add('survey_id', 'custom', [
'rule' => function ($value, $context) {
if (!empty($context['data']['projectId'])) { $values = array($context['data']['projectId']); } else { $values = array(); }
$data = $this->getSurveyId($value, $values);
return (!empty($data)) ? false : true;
},
'message' => __('msg_surveyid_exsist')]);
return $validator;
}
public function getSurveyId($surveyId = null, $exclude = null) {
$where = array('p.survey_id' => $surveyId);
if (!empty($exclude) && is_array($exclude)) {
$where[] = array('p.id NOT IN' => $exclude);
}
return $this->db->newQuery()
->select('*')
->from(['p' => 'projects'])
->where($where)
->execute()
->fetch('assoc');
}

Laravel Simultaneously input one to many in database

I have a card, this card has tags. So a Card has many tags and a Tag belongsTo a Card.
A user fills a form. He gives both the information for the card aswell as the tags.
Now I need to give each tag the information 'card_id' so it can be connected.
Now is my problem that I don't know this 'card_id' yet because the database did not yet assign a id as they are both being created simultaneously.
My situation:
public function create(Request $request)
{
$this->validate($request,[
'function' => 'max:255',
'description' => 'max:255',
'rate' => 'max:255',
'location' => 'max:255'
]);
$card = new Card;
$card->user_id = Auth::id();;
$card->function = $request->function;
$card->description = $request->description;
$card->rate = $request->rate;
$card->location = $request->location;
// I also tried this: $card->tag()->saveMany($tagsArray); (Did not work)
$card->save();
$tagsArray = explode(',', $request->tagsarray);
foreach($tagsArray as $tagInput) {
$tag = new Tag;
$tag->card_id = 'Cant know this yet :(';
$tag->tag = $tagInput;
$tag->save();
}
return redirect('/page');
}
Does someone know how to go about this?
You may try something like this:
$card = new Card([
'card_name' => request()->get('card_name'),
'something_else' => request()->get('something_else')
]);
if($card->save()) {
$tags = [];
// Get the tag information from request
$tagsFromRequest[
['tag_title' => 'A Tag', 'tag_slug' => 'a_tag'],
['tag_title' => 'Another Tag', 'tag_slug' => 'another_tag']
];
foreach($tagsFromRequest as $tag) {
$tags[] = new Tag($tag);
}
$card->tags()->saveMany($tags);
}
Now, prepare your tags from request where each tag item should be an array as given above and I can't be more specific because you gave nothing that you've tried and which might help me to understand your scenario. Check the documentation.

Update profile function

I have a function that check updates the users profile info. Currently, if I put |unique:users in the validator every time I try to update the profile info on the form it will not let me because a user (which is me) has my email. So I figured out the unique means that nobody, including the current user can have the email that is being updated.
So I need to compare the current auth email to the one in the database. If it matches then it is ok to update the profile info. I know this is simple but I am not sure how to implement it and if that is the right logic.
So where in this code would I post if (Auth::user()->email == $email){..update email...} http://laravel.io/bin/GylBV#6 Also, is that the right way to do this?
public function editProfileFormSubmit()
{
$msg = 'Successfully Updated';
$user_id = Auth::id();
$user = User::find($user_id);
$first_name = Input::get('first_name');
$last_name = Input::get('last_name');
$email = Input::get('email');
$phone_number = Input::get('phone_number');
$validator = Validator::make(Input::all(), array(
'email' => 'required|email',
'first_name' => 'required',
'last_name' => 'required',
'phone_number' => 'required'
));
if ($validator->fails()) {
return Redirect::route('edit-profile')
->withErrors($validator)
->withInput();
}else{
if(Input::hasFile('picture')){
$picture = Input::file('picture');
$type = $picture->getClientMimeType();
$full_image = Auth::id().'.'.$picture->getClientOriginalExtension();
if($type == 'image/png' || $type == 'image/jpg' || $type == 'image/jpeg'){
$upload_success = $picture->move(base_path().'/images/persons/',
$full_image);
if($upload_success) {
$user->picture = $full_image;
} else {
$msg = 'Failed to upload picture.';
}
}else{
$msg = 'Incorrect image format.';
}
}
$user->first_name = $first_name;
$user->last_name = $last_name;
$user->email = $email;
$user->phone_number = $phone_number;
$user->save();
return Redirect::route('invite')->with('global', $msg);
}
}
Worry not, Laravel has already considered this potential issue! If you take a look at the docs for the unique validation rule you'll see that it can take some extra parameters. As it happens, you can give it an id to ignore when looking at the unique constraint. So what you need to do is work out the id for the current model to update and pass that in. In the case of updating a logged-in user's profile it's made easy by Auth::id() as you already have in your code.
$rules = [
'email' => ['required', 'email', 'unique:users,email,'.Auth::id()],
'first_name' => ['required'],
// etc...
];
Obviously I chose to use the array syntax for validation rules there, but you can do the same with the pip syntax too. In a less specific system (create-or-add in a crud postSave type action) you can still do it by simply dong something like $model = Post::find($id) and then if $model is null you're creating and you just use 'unique' whereas if $model is not null, use 'unique:table,field,'.$model->getKey().

Resources