laravel unique validation on foreign key - laravel

I have database table streets in which I am storing name and block_id as foreign key from the blocks table. So I want the name of street should be unique in every block. for example if the name of street is street 1 with block_id 1, it should not be added again with block_id 1 but it should be allowed to add street 1 with block_id 2 or 3. How can I get it with Laravel validation?
My validation Code:
here you can see I am validating uniqueness only on those records which have delete = false.
$validatedValues = $request->validate([
'block' => 'required',
'street' => [
'required',
Rule::unique('streets', 'sName')->where(function ($query) {
return $query->where('delete', false);
})
],
'street_width' => 'required',
]);

Replace this with street key in your code
'name' => [
'required',
Rule::unique('streets')->where(function ($query) use($request) {
return $query->where('name', $request->name)
->where('block_id', $request->block_id);
}),
],

try this one
Create request -> PHP artisan make:request StreetsRequest
in ur controller find the store method or whatever the name u put for storing ur data, and change the (Request $request) to (StreetsRequest $request)
use App\Http\Requests\StreetsRequest;
....
public function store(StreetsRequest $request){
$request->validated();
// Do whatever u want after validate
}
Open your StreetsRequest file and inside the return [] put sth like this
use Illuminate\Validation\Rule;
...
'block_id' => [
'required',
Rule::unique('streets','block_id')->ignore(request('id')),
],
i hope it will work , let us know if u still have any problem, thx
check laravel validation for more
[https://laravel.com/docs/8.x/validation#form-request-validation]

You can try writing custom validation for that
$validator = $request->validate([
'block' => 'required',
'street' => [
function ($attribute, $value, $fail) use($request){
$street= Street::where('delete', false)->where(function ($query)use($request){
$query->where('sName',$request->sName);
$query->where('block_id',$request->block_id );
})->exists();
if($street){
$fail('The '.$attribute.' is invalid.');
}
},
],
]);
I hope for streets table you have Street model
if any issue let me know .

Related

How to validate unique more than one field in Laravel 9?

I want to do validate when store and update data in Laravel 9. My question is how to do that validate unique more than one field?
I want to store data, that is validate formId and kecamatanId only one data stored in database.
For example:
formId: 1
kecamatanId: 1
if user save the same formId and kecamatanId value, its cant saved, and show the validation message.
But if user save:
formId: 1,
kecamatanId: 2
Its will successfully saved.
And then user save again with:
formId: 1,
kecamatanId: 2
It cant saved, because its already saved with the same condition formId and kecamatanId.
My current validate code:
$this->validate($request, [
'formId' => 'required|unique:data_masters',
'kecamatanId' => 'required',
'level' => 'required',
'fieldDatas' => 'required'
]);
Update:
I have try:
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
$formId = $request->formId;
$kecamatanId = $request->kecamatanId;
Validator::make($request, [
'formId' => [
'required',
Rule::unique('data_masters')->where(function ($query) use ($formId, $kecamatanId) {
return $query->where('formId', $formId)->where('kecamatanId', $kecamatanId);
}),
],
]);
But its return error:
Illuminate\Validation\Factory::make(): Argument #1 ($data) must be of type array, Illuminate\Http\Request given, called in /Volumes/project_name/vendor/laravel/framework/src/Illuminate/Support/Facades/Facade.php on line 338
You can dry using the different:field rule : which validate that the validated field must be different to the given field;
$this->validate($request,[
'formId' => ['unique:users'],
'kecamatanId' => [
'required',
Rule::unique('users')->where(fn($query) => $query->where('formId', $request->input('formId')))
]
]);

Laravel - Unique Request Rules allows duplicate

In Laravel-5.8 I applied Rules Request for multiple fields as shown below:
public function rules()
{
return [
'goal_type_id' => [
'required',
Rule::unique('appraisal_goals')->where(function ($query) {
return $query
->where('employee_id', 1)
->where('appraisal_identity_id', 1);
})
],
'appraisal_doc' => 'nullable|mimes:doc,docx,xls,xlsx,ppt,pptx,pdf,jpg,jpeg,bmp,png,|max:5000',
'weighted_score' => 'required|numeric|min:0|max:500',
];
}
This is mysql query:
ALTER TABLE appraisal_goals
ADD CONSTRAINT appraisal_goals_uniq1 UNIQUE KEY(goal_type_id,appraisal_identity_id,employee_id);
This is meant for create. From the code the combination of goal_type_id, employee_id and appraisal_identity_id are unique.
When I click on submit in create blade, it allows duplicate.
How do I resolve this?
Also, how do I write the one for update?
Please note that my route is appraisal_goal
Thank you
Try this code for update
public function rules()
{
$appraisal_goal_id = 'take your appraisal_goals id here from request';
return [
'goal_type_id' => [
'required',
Rule::unique('appraisal_goals')->ignore($appraisal_goal_id, 'id')->where(function ($query) {
return $query
->where('employee_id', 1)
->where('appraisal_identity_id', 1);
})
],
'appraisal_doc' => 'nullable|mimes:doc,docx,xls,xlsx,ppt,pptx,pdf,jpg,jpeg,bmp,png,|max:5000',
'weighted_score' => 'required|numeric|min:0|max:500',
];
}

Laravel send mail with multiple check box value

i'm trying to make inquiry form where costumer fill up form then check the value on the checkbox then once they submit form will send email to me listing all the information the customer selected, now problem is i want to change this[event_id,requirement_id] instead of id replace it with name those two id parameter is from my two model listed below.
Model:
Event:[id,name]
Requirement:[id,name]
Controller:
public function store(Request $request)
{
$summary=[
'name' => $request->fullname,
'email' => $request->email,
'company' => $request->company,
'event' => $request->event_id,
'requirement' => $request->requirement_id
];
return $summary;
Mail::send('emails.contact-message',[
],function($mail) use($summary){
$mail->from('myemail#gmail.com', 'tester');
$mail->to('myemail#gmail.com')->subject('Contact Message');
});
return redirect()->back();
}
This is the result of my return request:
{"name":"myname","email":"myemail#gmail.com","company":"mycompany","event":["1","2"],"requirement":["1","2"]}
As you can see the array Event has value of 1 and 2 i wanted to replace it with its name output should be [Wedding,Birthday] i'm sorry for my bad english hope you understand me..
Well, you'd need to pull the name from your models.
The following should do the trick:
$events = App\Event::whereIn('id', $request->event_id)
->get()
->pluck('name')
->toArray();
$requirements = App\Requirement::whereIn('id', $request->requirement_id)
->get()
->pluck('name')
->toArray();
Obviously, replace name in the above example with the actual name field in your models. This is just an example.
$events and $requirements will both be an array containing the names matching the ids you are supplying in your request.
You also need to change your $summary array as follows:
$summary = [
'name' => $request->fullname,
'email' => $request->email,
'company' => $request->company,
'event' => $events
'requirement' => $requirements
];

Right way to handle this situation using Laravel validation

i am new in Laravel and I would like to have some directive on how to handle this situation.
I have two entities: Ad and Nomination. Ad can have many Nominations.
In a controller i receive two external inputs: [ad_id] and [nomination_id] both required.
What i have to do with these two inputs is:
Check if [ad_id] is an existing Ad entity and his attribute "active" is true.
Check [nomination_id] is an existing Nomination entity.
Only if [ad_id] was an existing Ad and [nomination_id] was an existing Nomination check if this Nomination belongs to this Ad.
Can you show me an example about how to manage this using only validation class?
You can write your validation rules like this
public function rules()
{
return [
'ad_id' => [
'bail',
'required',
Rule::exists('ads')->where(function ($query) use ($request) {
$query->where([
['active' => 1],
['id' => $request->ad_id]
]);
}),
],
'nomination_id' => [
'bail',
'required',
Rule::exists('nominations')->where(function ($query) use ($request) {
$query->where([
['ad_id' => $request->ad_id],
['id' => $request->nomination_id]
]);
}),
],
];
}
Assuming you have ads and nominations are tables name and primary key field is id and ad_id as foreign key in nominations table.
It's pretty straightforward - you can write validation rules just as you listed them in your question:
$validator = Validator::make($request->only('ad_id', 'nomination_id'), [
'ad_id' => 'required|exists:ads,id,active,1',
'nomination_id' => 'required|exists:nominations,id,ad_id,' . $request->ad_id,
]);
if ($validator->fails()) {
...
}
$inputAd = <some_value>;
$inputNomination = <some_value>;
$nomination = Nomination::where(['id' => $inputNomination])->with(['ads'])->first();
if(!$nomination || !($nomination->ad_id == $inputAd)) {
// not the same
}
// same
To validate the ad_id and nomination_id, you can use laravel in rule.
FormRequest Class
public function rules()
{
return [
'ad_id' => [
'required',
Rule::in(Ad::where('active', true)->pluck('id')->toArray()),
],
'nomination_id' => [
'required',
Rule::in(Nomination::where('id', $this->nomination_id)->where('ad_id', $this->ad_id)->pluck('id')->toArray()),
],
];
}
The Rule::in(Ad::where('active', true)->pluck('id')->toArray()), rule will check if the ad_id is present in the array of ids of Ad which have active field is true.
The Rule::in(Nomination::where('id', $this->nomination_id)->where('ad_id', $this->ad_id)->pluck('id')->toArray()), rule will check if the nomination_id is present in the array of ids of Nomination which is related to Ad.

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

Resources