Validate whether multiple fields are unique simultaneously in laravel 5 - laravel-5

This my request class rules.
return [
'title' => 'required|unique:event_cals,title',
'eventDate' => 'required|date|after:yesterday',
'venue' => 'required',
'time' => 'required',
'type' => 'required',
'unique:event_cals,eventDate,NULL,id,venue,$request->venue,time,$request->time'
];
I want to validate a rule like below.
'eventDate' && 'venue' && 'time' => 'unique'
There I need to check if there any row without same eventDate, venue and time altogether. Anyone knows how to declare such a rule?
This is the snapshot of db table.

Here is the possible solution:
<?php
return [
'title' => 'required|unique:event_cals,title',
'eventDate' => 'required|date|after:yesterday',
'venue' => 'required',
'time' => 'required',
'type' => 'required',
'event_date' => "unique:event_cals,event_date,NULL,id,venue,{$request->venue},time,{$request->time}",
];
I again want to highlight that; if you want that validator to work, you should make sure that the event_date and time should be correctly formatted.
An example unique check with additional wheres from our running project's update requests:
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
$id = $this->route('money');
return $rules = [
'name' => "required|string|min:3|max:255|unique:moneys,name,{$id},id,deleted_at,NULL,access,public",
];
}

Related

Multiple inputs in one validation rule

return [
'contract_code' => 'required',
'name' => 'required|string',
'abbreviation' => 'required|string',
'linecount_divisor' => 'required|integer'
];
// into input fields => 'required'
How to shorten the validation rule in multiple inputs?
if You have the same validation rule for multiple and you want to shorten your code just use form requests.
php artisan make:request RequestName
And then in the controller Functions use it
public function save(RequestName $requestName)
{
}
don't forget to use that request class.
use App\Http\Requests\RequestName;
Here is a solution assuming all input fields need to have a common rule like required.
$rules = array_map(function($curr) { return [$curr => 'required']; }, array_keys(request()->all()));
Try this one in Laravel
$validation=array();
$validation= [
'contract_code' => 'required',
'name' => 'required|string',
'abbreviation' => 'required|string',
'linecount_divisor' => 'required|integer'
];
$this->validate($request,$validation);

Laravel one validation function for Store and Update

I am trying to have one validation function for both store and update. So I don't repeat code. It works well. The problem is testing 'unique'. I worked around with this idea. But feels long-winded. Is there a better way to do it?
I want to check for unique at the store.
At update, unique check ignores own id.
I don't want different validations like I did as the user will be
first notified of the unique error, he will fix it. then something
else might be wrong and he has to fix again.
.
public function validateRequest($request){
if($request->method() == "PUT")
{
$val = $this->validate($request, [
'name' => 'unique:customers,id',
'phone' => 'unique:customers,id',
]);
}
if($request->method() == "POST"){
$val = $this->validate($request, [
'name' => 'unique:customers',
'phone' => 'unique:customers'
]);
}
$validation = $this->validate($request, [
'name' => 'required',
'phone' => 'required|integer|gt:0',
'phone2' => 'nullable|integer|gt:0|',
'email' => 'email|nullable',
'note' => 'nullable',
],
[
'phone.integer' => "Invalid phone format. Use international format. Eg: 971550000000",
'phone2.integer' => "Invalid phone format. Use international format. Eg: 971550000000",
'required' => "Required Field",
]);
return $validation;
}

Do Unique validation on multiple fields in Laravel 5.8

I want to do "unique" validation on multiple fields. I have written below validation rule but not sure how to include brand_id and company_id in it
$request->validate([
'name' => 'required|string|unique:products',
'company_id' => 'required',
'brand_id' => 'required',
]);
So what I am trying to do is, ADD PRODUCT but check if the name is unique for the given company_id and brand_id. How can I do that?
We can use Rule::unique() function to add custom conditions to unique validation.
$request->validate([
'company_id' => 'required',
'brand_id' => 'required',
'name' => [
'required',
'string',
Rule::unique('products')->where(function($query) {
$query->where('company_id', request('company_id'));
$query->where('brand_id', request('brand_id'));
}),
],
]);
Sometimes you may wish to stop running validation rules on an attribute after the first validation failure. To do so, assign the bail rule to the attribute:
$request->validate([
'name' => 'bail|required|string|unique:products',
'company_id' => 'bail|required',
'brand_id' => 'required',
]);
You can add additional wheres after the ignore options (the NULL,id below), e.g.:
$request->validate([
'company_id' => 'required',
'brand_id' => 'required',
'name' => 'required|string|unique:products,name,NULL,id,company_id,'.request('company_id').',brand_id,'.request('brand_id'), '
]);

Validation : Laravel

In ContactsRequest.php
public function rules()
{
return [
'org_id' => 'required',
'name' => 'required',
'office' => 'required',
'mobile' => 'required_without:home',
'home' => 'required_without:mobile'
];
}
So basically what i want is , i have a form which will be taking the attributes specified in the code. But i want to modify code so that entering either one of 'home' or 'mobile' will allow me to create the new user.
What should be done.Any help would be appreciated

Custom request validators for Multiple arrayed inputs

I have 1 form, with multiple inputs. each section can have multiple inputs, I want to create a Form Validator inside Requests for they, but don't know how to do it... This is currently how I am doing it:
public function postCreateResume(Request $request, Resume $resume, Education $education)
{
/*
* begin a transaction, because we
* are doing multiple queries
*/
DB::beginTransaction();
/*
* first we must create the resume, then we
* can use the id for the following rows
*/
$this->validate($education, [
'resume_title' => 'required',
'expected_level' => 'required',
'salary' => 'required',
'work_location' => 'required',
'year_experience' => 'required',
'about' => 'required',
]);
$resume->name = $request['resume_title'];
$resume->work_level = $request['expected_level'];
$resume->salary = $request['expected_salary'];
$resume->country = $request['work_location'];
$resume->total_experience = $request['year_experience'];
$resume->about = $request['about'];
$resume->save();
// a user can have multiple educations on their cv
foreach($request->input('education') as $education){
$this->validate($education, [
'institution' => 'required',
'degree' => 'required',
'year_begin' => 'required',
'year_finish' => 'required',
'about' => 'required',
]);
// passed our checks, insert
$education->resume_id = $resume->id;
$education->user_id = Auth::user()->id;
$education->institute = $education['institution'];
$education->degree = $education['degree'];
$education->summary = $education['about'];
$education->started = $education['year_begin'];
$education->ended = $education['year_finish'];
if(!$education->save()){
DB::rollback();
return redirect()->back()->withErrors("There was an error creating this resume")->withInput();
}
}
// a user can have multiple employment on their cv
foreach($request->input('experience') as $employment){
$this->validate($employment, [
'company' => 'required',
'title' => 'required',
'country' => 'required',
'year_begin' => 'required',
'year_finish' => 'required',
'notes' => 'required',
]);
// passed our checks, insert
$employment->resume_id = $resume->id;
$employment->user_id = Auth::user()->id;
$employment->name = $employment['title'];
$employment->company = $employment['company'];
$employment->country = $employment['country'];
$employment->started = $employment['year_begin'];
$employment->ended = $employment['year_finish'];
$employment->summary = $employment['notes'];
if(!$employment->save()){
DB::rollback();
return redirect()->back()->withErrors("There was an error creating this resume")->withInput();
}
}
return redirect()->back()->withSuccess("You have created a resume")->withInput();
}
Notice I have the validate inside each of the foreach in case the user has chosen more than 1 (in this example) work experience, or education, what I am trying to do is move the $this->validate inside the Requests folder, how can I achieve this?
I am using a foreach because I can have unlimited sections, see the image as to why;
Since laravel 5.4 you can pass arrays to the validator itself, for exaple
<input name="myarray[0]['test'] type="text">
Can now be validated like so
$this->validate($request, [
'myarray.*.test' => 'required'
]);
https://laravel.com/docs/5.4/validation#validating-arrays
Validating array based form input fields doesn't have to be a pain. For example, to validate that each e-mail in a given array input field is unique, you may do the following:
$validator = Validator::make($request->all(), [
'person.*.email' => 'email|unique:users',
'person.*.first_name' => 'required_with:person.*.last_name',
]);
Likewise, you may use the * character when specifying your validation messages in your language files, making it a breeze to use a single validation message for array based fields:
'custom' => [
'person.*.email' => [
'unique' => 'Each person must have a unique e-mail address',
]
],

Resources