I have the following request validation rules in an controller.
public function __invoke(Request $request)
{
$this->validate($request, [
'name' => ['required', 'unique:games,name', 'string'],
'variant' => ['required', 'string'],
'rules' => ['string'],
'is_anonymous' => ['boolean', 'required'],
'message_mode' => ['required', new EnumRule(MessageModeEnum::class)],
'powers' => ['required', 'array'],
'powers.*' => ['distinct:ignore_case', 'required', 'string'],
]);
}
Below is the test I'm running against the controller. I would expect the powers.* validation to throw an error as the two powers are equal and not distinct.
/**
* #test
*
*/
public function endpoint_validation()
{
$user = User::factory()->create(['rank' => RankEnum::A()]);
$response = $this->actingAs($user)->post(route('game.create'), [
'name' => '::name::',
'variant' => '::variant::',
'rules' => '::rules::',
'is_anonymous' => false,
'message_mode' => 'none',
'powers' => [
'::power::', '::power::'
],);
$response->assertSessionHasErrors('powers');
}
However, this test is failing. What am I doing wrong? How can I fix this?
Related
At my registration form, i have a bool input as newCompany with values
0=register to existed company with company code
1=create new company
Using required_if validation at different fields. And if it fails throws a validation message like "The Company Code field is required when Company is 0."
I wanna set that 0 value as Existing for 0 and New for 1. So i'm inserted them to my language file and changed :value attribute for default error message at lang/en/validation.php file.
'required_if' => 'The :attribute field is required when :other is :value.'
Here's my app/Requests/AuthRegisterRequest.php file:
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rules\Password;
use Illuminate\Validation\Rules\File;
use Illuminate\Http\Request;
class AuthRegisterRequest extends FormRequest {
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize() {
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array<string, mixed>
*/
public function rules(Request $request) {
return [
'name' => 'required|max:50|alpha',
'surname' => 'required|max:50|alpha',
'email' => 'required|email|unique:users,email',
'password' => [
'required',
Password::min(8)->numbers()->letters()->uncompromised(5)
],
'c_password' => 'required|same:password',
'newCompany' => 'required|boolean',
'companyCode' => 'nullable|required_if:newCompany,0|max:20|exists:user_companies,code',
'companyName' => 'nullable|required_if:newCompany,1|max:255',
'companyPhone' => 'nullable|required_if:newCompany,1|max:50|unique:user_companies,phone',
'activityTaxDocument' => [
'nullable',
'required_if:newCompany,1',
File::types(['jpg, jpeg, gif, png, doc, docx, pdf'])->max(5*1024) //5 MB
],
'privacyPolicies' => 'required|boolean'
];
}
public function attributes() {
return __('fieldname.AuthRegister');
}
public function messages() {
return [
'companyCode.required_if'=>__('validation.required_if', [
'value'=>__('fieldname.AuthRegister.newCompanyValues')['0']
]),
'companyName.required_if'=>__('validation.required_if', [
'value'=>__('fieldname.AuthRegister.newCompanyValues')['1']
]),
'companyPhone.required_if'=>__('validation.required_if', [
'value'=>__('fieldname.AuthRegister.newCompanyValues')['1']
]),
'activityTaxDocument.required_if'=>__('validation.required_if', [
'value'=>__('fieldname.AuthRegister.newCompanyValues')['1']
])
];
}
}
And lang/en/fieldname.php file
<?php
return [
'AuthRegister' => [
'name' => 'Name',
'surname' => 'Surname',
'email' => 'Email',
'password' => 'Password',
'c_password' => 'Confirm Password',
'newCompany' => 'Company',
'companyCode' => 'Company Code',
'companyName' => 'Company Name',
'companyPhone' => 'Company Phone',
'activityTaxDocument' => 'Activity/Tax Document',
'privacyPolicies' => 'Privacy Policy & Terms',
'newCompanyValues' => [
'1' => 'New',
'0' => 'Existing'
]
]
];
It's working but i wanna combine message for required_if validation to shorten the code according to newCompany field. But couldn't get input values at messages function.
Tried:
public function messages(Request $request) {
return [
'required_if'=>__('validation.required_if', [
'value'=>__('fieldname.AuthRegister.newCompanyValues')[$request->newCompany]
])
];
}
But it throws 500 with error below
{
"message": "Declaration of App\\Http\\Requests\\AuthRegisterRequest::messages(Illuminate\\Http\\Request $request) must be compatible with Illuminate\\Foundation\\Http\\FormRequest::messages()",
"exception": "Symfony\\Component\\ErrorHandler\\Error\\FatalError",
"file": "/var/www/html/app/Http/Requests/AuthRegisterRequest.php",
"line": 67,
"trace": []
}
I have a lot of forms like this. Some of them have much much more fields changing according a bool field. Is there a way to get input values at messages function or capture it from somewhere else?
if not, is it worth to defining a new rule, or should i just define it for each field separately?
Thanks.
I think you can use sometimes method without message() method
public function rules(Request $request) {
return [
'name' => 'required|max:50|alpha',
'surname' => 'required|max:50|alpha',
'email' => 'required|email|unique:users,email',
'password' => [
'required',
Password::min(8)->numbers()->letters()->uncompromised(5)
],
'c_password' => 'required|same:password',
'newCompany' => 'required|boolean',
'companyCode' => 'nullable|sometimes|required_if:newCompany,0|max:20|exists:user_companies,code',
'companyName' => 'nullable|sometimes|required_if:newCompany,1|max:255',
'companyPhone' => 'nullable|sometimes|required_if:newCompany,1|max:50|unique:user_companies,phone',
'activityTaxDocument' => [
'nullable',
'sometimes',
'required_if:newCompany,1',
File::types(['jpg, jpeg, gif, png, doc, docx, pdf'])->max(5*1024) //5 MB
],
'privacyPolicies' => 'required|boolean'
];
}
I have two tables "rooms" and "beds" i want to unique bed name when room_id is same. what should i do.
public function store(Request $request)
{
$roomid = $request->input('room_id');
//
$attributes = request()->validate([
'room_id' => ['required', 'integer', 'min:1'],
'name' => ['required', 'string', 'min:1', 'max:10', 'unique:App\Models\bed,name,room_id' . $roomid],
'type' => ['nullable', 'string', 'min:1', 'max:10'],
'description' => ['nullable', 'string', 'min:1', 'max:20']
]);
bed::create($attributes);
}
~~~
You should use closures instead of a rule object because this validation doesn't seem to be necessary throughout your application and you need it only here.
Change your validation to this:
$attributes = request()->validate([
'room_id' => ['required', 'integer', 'min:1'],
'name' => [
'required', 'string', 'min:1','max:10',
function ($attribute, $value, $fail) {
// Checke if name is unique in that room
$name_exists = \App\Models\Bed::where('name', $value)->where('room_id', request()->input('room_id'))->count() > 0;
if ($name_exists) {
$fail('The '.$attribute.' must be unique in this room.');
}
}
],
'type' => ['nullable', 'string', 'min:1', 'max:10'],
'description' => ['nullable', 'string', 'min:1', 'max:20']
]);
Source
solved
use Illuminate\Validation\Rule;
public function store(Request $request)
{
$roomid = $request->input('room_id');
$attributes = request()->validate([
'room_id' => ['required', 'integer', 'min:1'],
'name' => [
'required',
'string',
'min:1',
'max:10',
Rule::unique('beds')
->where(function ($query) {
return $query->where('room_id', request('room_id'));
})
],
'type' => ['nullable', 'string', 'min:1', 'max:10'],
'description' => ['nullable', 'string', 'min:1', 'max:20'],
]);
bed::create($attributes);
}
I tried insert ads using validation system but its give me error:
Argument 1 passed to Illuminate\Validation\Factory::make() must be of the type array, object given, called in D:\wamp\www\pagination\vendor\laravel\framework\src\Illuminate\Support\Facades\Facade.php on line 261
AdsController.php
public function store(Request $request)
{
$file = new File($request->all());
$file->user_id = Auth::user()->id;
$validator = Validator::make($file->all(), [
'category_id'=>['bail','required'],
'titre' => ['bail', 'exclude_unless:category_id,1', 'required', 'string', 'min:3', 'max:255'],
'name' => ['bail', 'exclude_unless:category_id,2', 'required', 'string', 'min:3', 'max:255'],
'last' => ['bail', 'exclude_unless:category_id,1', 'required', 'string', 'min:3', 'max:255'],
]);
File::create($validator->validated());
return Redirect::to("/")
->withSuccess('Great! file has been successfully uploaded.');
}
You just need to pass $request->all() as the first argument to Validator::make().
...
$validator = Validator::make($request->all(), [
/* validation rules */
];
...
And I think 'title' is misspelled in your validation rules (titre);
sometimes this errors comes when you use this:
'$validator = Validator::make($request->all, [
'file' => 'requeired|max:7000|mimes:xlsx,xls,csv'
]);' instead of this $validator = Validator::make($request->all(), [
'file' => 'requeired|max:7000|mimes:xlsx,xls,csv'
]);
I'm trying to apply these validation rules to my controller function, but any of the rules are not applying
Here is my code
if($request->hasFile('propic'))
{
$this->validate($request, [
'name' => 'required', 'alpha','min:2', 'max:255',
'last_name' => 'required', 'alpha','min:5', 'max:255',
'mobile' => 'required', 'string','min:10','max:14', 'regex:/\+(9[976]\d|8[987530]\d|6[987]\d|5[90]\d|42\d|3[875]\d|
2[98654321]\d|9[8543210]|8[6421]|6[6543210]|5[87654321]|
4[987654310]|3[9643210]|2[70]|7|1)\d{1,14}$/',
'email' => 'required', 'string', 'email', 'max:255', 'unique:users,email,'.$setting->id.'',
'propic' => 'required','image','mimes:jpeg,png,jpg,gif,svg','max:2048',
]);
$imageName = time().'.'.$request->propic->extension();
$request->propic->move(public_path('propics'), $imageName);
$setting->propic=$imageName;
$setting->name=$request->input('name');
$setting->last_name=$request->input('last_name');
$setting->mobile=$request->input('mobile');
$setting->email=$request->input('email');
$setting->update();
return Redirect::back()->with('success',__('sentence.User updated successfully'));
}
At time of writing, there's two accepted formats for passing in validation rules:
As an array of strings (note the square brackets, which is what you are missing currently):
$this->validate($request, [
'name' => ['required', 'alpha','min:2', 'max:255'],
...
]);
As a single pipe-delimited string:
$this->validate($request, [
'name' => 'required|alpha|min:2|max:255',
...
]);
My validation fails with this:
$this->validate($request, [
'name' => ['required'],
'email' => ['required', 'email', 'unique:organisers',$organiser->id,'organisers_id'],
'organiser_logo' => ['mimes:jpeg,jpg,png', 'max:10000'],
]);
but it works with this:
$this->validate($request, [
'name' => ['required'],
'email' => ['required', 'email', 'unique:organisers'],
'organiser_logo' => ['mimes:jpeg,jpg,png', 'max:10000'],
]);
This:
'unique:organisers',$organiser->id,'organisers_id'
needs to be:
'unique:organisers,'.$organiser->id.',organisers_id'
or (note the double-quotes):
"unique:organisers,{$organiser->id},organisers_id"
The , means "new array element", the . means "add to this string".