Is it possible to conditionally set a custom language file (eg resources/lang/en/validation_ajax.php
) for a validation request? Just to be clear, I don't want to change the app language, just use another set of messages depending on the request origin.
When I make an ajax validation call I want to use different messages since I'm showing the error messages below the field itself. So there's no need to show the field name (label) again.
I know you can define labels on 'attributes' => []
but it's not worth the effort since I have so many fields in several languages.
I'm using a FormRequest (there's no manual call on the Controller just a type hint).
You can override the messages()
method for a specific request (let's say login request). Let me show you: At first place, you need yo create a new custom Form Request, here we will define a custom message for email.required
rule:
<?php namespace App\MyPackage\Requests;
use App\Http\Requests\Request;
class LoginRequest extends Request {
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
public function messages()
{
return [
'email.required' => 'how about the email?',
];
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'email' => ['required', 'email'],
'password' => ['required', 'confirmed']
];
}
}
Only
email.required
rule message will be override. For password it will display the default message set atvalidation.php
file.
Now, apply the form request at your controller function like a type hint:
class LoginController{
public function validateCredentials(LoginRequest $request){
// do tasks here if rules were success
}
}
And that is all. The messages()
method is useful if you need are creating custom packages and you want to add/edit validation messages.
If you need to carry the bag of messages on into your package's lang file then you can make the following changes:
At your package create your custom lang file:
MyPackage/resources/lang/en/validation.php
Add the messages keeping the same array's structure as project/resources/lang/en/validation.php
file:
<?php return [ 'email' => [ 'required' => 'how about the email?', 'email' => 'how about the email format?', ], ];
Finally, at your messages()
method call the lang's line of your package respectively:
public function messages(){ return [ 'email.required' => trans('myPackage::validation.email.required'), 'email.emial' => trans('myPackage::validation.email.valid'), ]; }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.