Laravel Validate Checkbox Certain Value - laravel

I am simply needing to know how to validate my array of checkbox values to be in a certain list of values. So, I am using the "in:" validation rule as shown below, but it's returning the error that the value of the checked box is invalid. Do I need to do something different since it's an array of values sent via AJAX?
Controller:
if ($request->ajax())
{
/*Create record in UserType Model with the values from the Type checkboxes*/
$Type = Input::get('Type');
$this->validate($request, [
'Type' => 'required|in:A,B,C,D',
],[
'required' => 'You must select at least one.',
]);
foreach ($Type as $key => $value)
{
Auth::user()->userType()->create([
'profile_id' => Auth::user()->id,
'type' => $value,
]);
}
}
In my form, I have the following inputs...
<input type="checkbox" name="Type[]" value="A"/>
<input type="checkbox" name="Type[]" value="B"/>
<input type="checkbox" name="Type[]" value="C"/>
UPDATE:
So, I found in the Laravel documentation that you can validate arrays using * to get the key/values in an array. However, in my array it's just Type[] so I've tried the following with no luck.
$this->validate($request,[
'type.*' => 'required|in:A,B,C,D'
// or
'type*' => 'required|in:A,B,C,D'
]);
Just not working. I know I need to retrieve the array value something with the *.
UPDATE:
I was running Laravel 5.1 when this option for validation is only available in Laravel 5.2. Solved.

First: The required isn't necessary when using in because it must be A, B or C. That is like a "multiple" required already.
Second: As shown in the docs just use:
$this->validate($request,[
'Type.*' => 'in:A,B,C,D'
],[
'in' => 'You must select at least one.',
]);
As your Input array is named Type. That would validate all Inputs named Type.
To be clear the asteriks could be replaced by e.g. one to just validate the Input named Type[one]:
'Type.one' => 'in:A,B,C,D'
or if the Input would be named Type[one][name]
'Type.one.name' => 'in:A,B,C,D'

You try this
if($this->has('Type') && is_array($this->get('Type'))){
foreach($this->get('Type') as $key => $Type){
$rules['Type'.$key.'] = 'required|in:A,B,C,D';
}

In laravel 5 ..
$this->validate($request, [
'Type' => 'required|array'
]);
Worked for me for checkboxes

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 validate rule

I have two datepicker input fields: from and to. To ensure that field value to is greater than field value from, I use the after validation rule. Everything is fine up until I leave the from input value null. Because I am applying the validation rule using the input value from.
How can I combine the required and after validation rules without running into this problem?
$from = $request->input('from');
$from = Carbon::createFromFormat('Y-m-d\TH:i', $from)->format('Y-m-d H:i A');
$attributes= request()->validate([
'from' => 'required|date',
'to'=> 'nullable|date|after:'.$from,
]);
Data missing error while from input value is empty.
The laravel validation rule allows you to compare a field against another field. So you can simply add: after:from
See the documentation here.
$attributes = request()->validate([
'from' => 'required|date',
'to'=> 'nullable|date|after:from',
]);

Adding validation rules for form fields with same name but different models

In my Laravel 7 app, to have nicer error messages in forms, I am using custom validations attributes. For instance for the field id it shows inventory number needed when missing in the form field for submission. Now the issue is that I have several forms for different models in my app and there is ofc more than one id field. There is also an id which is an employee number or a process number.
But in resources/lang/en/validation.php I don't see a way to define the same field name for different models. My idea was to rename the field for error checking, e.g. id rename to employee_id but then no error message comes up.
From my view:
<div class="form-group{{ $errors->has('id') ? ' ' : '' }}">
<input class="form-control{{ $errors->has('id') ? ' is-invalid' : '' }}" name="id" type="text" value="{{ old('id', $process->id) }}" aria-required="true"/>
#include('alerts.feedback', ['field' => 'employee_id']) //not working
</div>
From my validation.php:
'attributes' => [
'email' => 'Mail Address',
'old_password' => 'Current Password',
'password' => 'Password',
'id' => 'Inventory Number', //working, for other form/model
'employee_id' => 'Employee ID' //not working
]
I think the issue is that only field names are accepted that actually exist in the database for the model. How to overcome this?
I just found the solution: A much better way to define custom error attributes than in the validation.php is to create a form request for the model (https://laravel.com/docs/7.x/validation#creating-form-requests) and use the method function attributes(). So there are no conflicts with other model field names and it's more clear, because the attributes are set in the model's form request:
<?php
namespace App\Http\Requests;
use App\Employee;
use Illuminate\Validation\Rule;
use Illuminate\Foundation\Http\FormRequest;
class EmployeeRequest extends FormRequest
{
(...)
public function attributes()
{
return [
'id' => 'Employee ID',
];
}
}
You can set custom messages when you validate your request, it would go something like this:
public function store(Request $request)
{
$request->validate([
'id' => 'required',
'employee_id' => 'required'
],
[
'id.required' => 'ID field is required',
'employee_id.required' => 'Employee field is required'
]);
}

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
];

Laravel 5.2 Validate File Array

I have a form with three fields: title, body and photo[]. I'm trying to validate it so that at least one item is filled in, but I can't seem to get it to work. If I upload a file I still receive an error for title and body.
public function rules()
{
return [
'title' => 'required_without_all:body,photo.*',
'body' => 'required_without_all:title,photo.*',
'photo.*' => 'required_without_all:title,body',
'photo.*' => 'mimes:jpeg,gif,png',
];
}
Update: Jonathan pointed out that I had my rules wrong. I've fixed them and am now using this. It's still not working; when I try to upload a photo I get the error message that the other fields are required.
public function rules()
{
return [
'title' => 'required_without:body,photo.*',
'body' => 'required_without:title,photo.*',
'photo.*' => 'required_without:title,body|mimes:jpeg,gif,png',
];
}
If you're looking to ensure the photo field is an array then you need 'photo' => 'array' and then you can use 'photo.*' => '' for the other validations of the array's children.
The rules are separated by a pipe character | so if you were going to combine the two in your example it would be 'photo.*' => 'required_without_all:title,body|mimes:jpeg,gif,png',. I don't see you using the pipe to separate rules so I can't be sure you are aware of it.
This may have been where you were going wrong in the first place (two keys in the associative array that are identical) and some kind of precedence taking affect negating one of the rules.
You could try something like this (for the record I think you were on the right track to begin with using required_without_all as this stipulates the need to be required if all of the given fields are missing):
public function rules()
{
return [
'title' => 'required_without_all:body,photo',
'body' => 'required_without_all:title,photo',
'photo' => 'array',
'photo.*' => 'required_without_all:title,body|mimes:jpeg,gif,png',
];
}
Reference

Resources