Laravel Form validation issue when form edit? - laravel

I used Laravel Form validation for validate form:
$rules = array(
'user_name' => 'required|min:3|max:20|unique:users',
'email' => 'required|email|max:50|unique:users',
'mobile' => 'required'
);
this is working well on some thing add. but when i going to edit unique:users part given error "already been taken", so how to write validation to check exclude edit row.
If I wrote this way, does it work?
$rules = array(
'user_name' => 'required|min:3|max:20|unique:users,'.$id,
'email' => 'required|email|max:50|unique:users,'.$id,
'mobile' => 'required'
);

#user3099298 Your second set of code looks alright.
$rules = array(
'user_name' => 'required|min:3|max:20|unique:users,user_name,' . $user_id, // $user_id = Currently being edited user id.
'email' => 'unique:users,email_address,' . $user_id, // $user_id = Currently being edited user id.
'mobile' => 'required',
);
I have added column names in rules - may be you can try that one.
Please check here the documentation
Where they explain how to ignore some rules by providing ID.

Related

Using Unique in Laravel

I am building a Book Portal with Laravel. I have a unique validation rule on name to books.
$request->validate([
'name' => 'required|unique:books',
'about' => 'required',
'dsecription' => 'required',
'image' => 'required|mimes:jpeg,bmp,jpg,png|between:1, 6000',
'author_id' => 'required',
'publisher' => 'required',
'recommended' => 'required',
'epub_url' => 'required',
'year'=> 'required',
'pages' => 'required',
]);
I found out that an Author can have the same book name. Using unique on the name, will not allow me to upload.
I am thinking, if there is a way, I can check the author and the name of the book i.e
Check if the author has the same name, then apply the unique rule on name else upload.
I didn't find any solution for this. That's why I made my own custom validation like this :
$request->validate([
'name' => 'required|unique:books',
'author_id' => 'required',
// ...
]);
$data = Book::where('author_id', $request->author_id)->where('name', $request->name)->first();
if(!empty($data)) {
return redirect()->back()->withErrors('This name already taken'); // error message
}
You can try using the extra where conditions that can be passed to the unique rule to apply the unique constraint under certain conditions:
// we will make sure 'author_id' is an existing value
'author_id' => 'bail|required|integer|exists:authors,id',
'name' => [
'bail',
'required',
Rule::unique('books')
->where('author_id', (int) $request->input('author_id')),
],
Assuming author_id is on the books table.
Laravel 7.x Docs - Validation - Rules - unique

How is it possible to retrieve the id of a Model right after it was created in the same controller function?

Let me show you my code, and place comments for you guys to better understand:
$homework = new Homework([ // I create Homework (And I indeed want to get the ID of the one that was just created).
'subject_id' => $request->subject_id,
'user_id' => auth()->user()->id,
'title' => $request->name,
'image' => $path,
'progress' => $request->progress,
'description' => $request->description,
'duedate' => $request->date
]);
$homework->save(); // I save it
$homeworkid = Homework::where('id', $id)->first(); // I try to retrieve it, but I'm not sure how to get it as I need to define `$id`.
$progress = newProgress([
'user_id' => auth()->user()->id,
'homework_id' => $homeworkid, // I need this for the relationship to work.
'title' => 'Initial Progress',
'description' => 'This progress is auto-generated when you create an assignment',
'username' => auth()->user()->name,
'progress' => $homeworkid->progress
]);
$progress->save(); // I save the progress
Well, as you saw, I'm trying to retrieve the ID of Homework right after it was created, but I'm not sure how to define $id in order to get it.
There is no need to instantiate a new model and saving it if your are not doing anything between instantiating and saving, you can use the create method instead:
$homework = Homework::create([
'subject_id' => $request->subject_id,
'user_id' => auth()->user()->id,
'title' => $request->name,
'image' => $path,
'progress' => $request->progress,
'description' => $request->description,
'duedate' => $request->date
]);
$homework->id; // get the id
After saving / creating the model you can access the id like you normally would:
$homework->id
What you then could do is setup the relationships between your models so you can do the following after creating a new homework:
$homework->newProgress()->create([
'user_id' => auth()->user()->id,
'title' => 'Initial Progress',
'description' => 'This progress is auto-generated when you create an assignment',
'username' => auth()->user()->name,
'progress' => $homework->progress
]);
This way you don't have to pass the homework id when creating a new newProgress, laravel will pass it automatically for you.
This is very simple for you. No need to complex it.
$homework->save(); // I save it
After this line just use only
$progress = newProgress([
'user_id' => auth()->user()->id,
'homework_id' => $homework->id, // I need this for the relationship to work.
'title' => 'Initial Progress',
'description' => 'This progress is auto-generated when you create an assignment',
'username' => auth()->user()->name,
'progress' => $homework->progress
]);
You don't no need this line of code
$homeworkid = Homework::where('id', $id)->first(); // I try to retrieve it, but I'm not sure how to get it as I need to define `$id`.
$data = $homework->save();
Get the ID this way: $data->id

How to Validate Record in Update Case in the Following Critical Situation using Laravel?

I want to update record but before update i want to check :-
1. if user exists at time not allowed to update.
Example :-
User jay try to update his name, but user insert same name which is already exists in jay field. at time i want to allow user to update but this code give error that username already exists. What i should do ??
Controller :-
public function update_data($update_id){
$gender_list = ['Male', 'Female', 'Other'];
$country_list = ['India', 'US', 'UK', 'Germany', 'Austraila'];
$Validator = $this->validate(request(), [
'username' => 'required|unique:userlists|alpha_num|max:30',
'email' => ['required', 'unique:userlists', 'email', 'regex:/((yahoo|gmail|hotmail)\.com)/'],
'password' => 'required',
'bod' => 'required|after_or_equal:today',
'comments' => 'required',
'phone_no' => 'required|numeric',
'country' => 'required|alpha',
'gender' => 'required',
'agreement' => 'required',
],[
'required' => 'Please Enter Your :attribute',
]);
if(!in_array($request->gender, $gender_list) || !in_array($request->country, $country_list)){
session()->flash('G_msg', 'Hello Hackes Please Go Back');
return back();
}
if($Validator->passes()){
// updation code.
}
}
You can use validation like below:
'username' => ['required','alpha_num', 'max:30',Rule::unique('userlists')->ignore($update_id)]
Make sure Rule is defined above Class:
use Illuminate\Validation\Rule;
try unique
'username' => 'required|unique:table_name,username,' . $update_id . ',user_id',
You may use Rule
use Illuminate\Validation\Rule;
'username' => ['required','alpha_num', 'max:30',Rule::unique('userlists')->ignore($update_id)]

How do i add more validation rules to a laravel validation array?

I have a laravel validation rules array that I have defined like this.
$rules = array(
'name' => 'required|regex:/(^[A-Za-z0-9 ]+$)+/',
'email' => 'required|email',
'mobile' => 'regex:/^\+?\d+$/',
);
$validation = Validator::make($input, $rules);
now depending on another if condition I want to add another validation rule into this array.
address => 'required'
how do I do it? I have tried the using array_push() function with the $rules array, but it doesn't work.
$rules['address'] = 'required';

Updating model - email is required to be unique [duplicate]

This question already has answers here:
Laravel 4 validation email unique constraint
(2 answers)
Closed 4 years ago.
I have a view that shows a form with pre-populated data related to a user model. This is for updating the model data. When the form is submitted, however, there's a conflict because the email address is not unique (if it hasn't been changed). Yet I still want to be able to store this (or ignore it).
I'm trying to update a model with this controller code:
$input = Input::all();
$validator = Validator::make($input, User::$rules['edit']);
if ($validator->fails()) {
return Response::json(array(
'error' => $validator->messages()
));
}
In the model, I've got:
public static $rules = array(
'create' => array(
'email' => 'required|email|unique:users',
'password' => 'required|confirmed',
'firstname' => 'required',
'lastname' => 'required',
'address_one'=> 'required',
'postcode'=> 'required'
),
'edit' => array(
'email' => 'sometimes|required|email|unique:users',
'password' => 'sometimes|required|confirmed'
),
);
But when I update, I get the error message:
"error": {
"email": [
"The email has already been taken."
]
}
I thought that the sometimes would stop this behaviour. What am I doing wrong?
You need to specify the user ID so the validator knows it needs to ignore the entry with that ID when checking the entries for uniqueness:
'email' => 'sometimes|required|email|unique:users,' . $id
Taken from the Laravel Docs:
Forcing A Unique Rule To Ignore A Given ID
'email' => 'unique:users,email_address,10'
In your case, since you're keeping the rules in a model property, you'll need to append the ID before passing the rules to the validator. Something like this should do:
$input = Input::all();
$rules = User::$rules['edit'];
// this assumes the user your want to update
// is stored in the $user variable
$rules['email'] .= ',' . $user->id;
$validator = Validator::make($input, $rules);
if ($validator->fails()) {
return Response::json(array(
'error' => $validator->messages()
));
}

Resources