Laravel: Custom validation messages in Custom Form Requests - php

I am trying to keep my controller clean and move the custom request validation in to a separate class as:
public function register(RegisterUserRequest $request)
and in there define all the usual functions, such as
public function rules(),
public function messages(), and
public function authorize()
However, the frontend is expecting the following data to display:
title (title related to the validation error message), description (which is the the actual validation error message), and status (=red, yellow etc)
How can I actually customise the response of the request?
Something like this, does not seem to be working:
protected function failedValidation(\Illuminate\Contracts\Validation\Validator $validator)
{
$response = new Response(['data' => [],
'meta' => [
'title' => 'Email Invalid'
'description' => '(The error message as being returned right now)',
'status' => 'red'
]);
throw new ValidationException($validator, $response);
}
Any ideas?

you can do this by making request in laravel as the following :
php artisan make:request FailedValidationRequest
this command will create class called FailedValidationRequest in
App\Http\Request directory and you cab write your rules inside this class as the following:
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class FailedValidationRequest 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
*/
public function rules()
{
return [
'title' => 'required'
'description' => 'required',
'status' => 'required|numeric'
];
}
}
and if you want to customize the error message you can download the language you want from this link using composer:
https://packagist.org/packages/caouecs/laravel-lang
and write the language you want by copying the languge folwder to the lang directory in your resource folder.
'custom' => [
'title' => [
'required' => 'your custom message goes here',
],
'decription' => [
'required' => 'your custom message goes here',
],
],

Related

how to detect if a field has input in laravel

I was trying to create a validation in laravel controller, where if one of the fields has input, then it will validate the rest of the fields to be 'required'. But it prompts Error
Class 'Illuminate\Support\Facades\Input' not found. Please help
if(Input::has('quantity1') || has('unit1') || has('dimension1') || has('price1')){
$data = $request->validate([
'quantity1' => 'required',
'unit1' => 'required',
'dimension1' => 'required',
'price1' => 'required',
]);
Use required_with laravel validation rule...
$data = $request->validate([
'quantity1' => 'required_with:unit1,dimension1,price1',
'unit1' => 'required_with:quantity1,dimension1,price1',
'dimension1' => 'required_with:quantity1,unit1,price1',
'price1' => 'required_with:quantity1,unit1,dimension1',
]);
Input is deprecated.
I would highly suggest creating a custom request class and using that.
The benfits include:
Conforming to SOLID principles.
Easy place to manage your rules and messages.
Easy place to handle permissions should you choose.
Can be extended and reused as needed.
--
Here are the steps how to do that:
Run php artisan make:request YourCustomRequestClassNamae
Fill the new app\Http\Requests\YourCustomRequestClassNamae.php file with:
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class YourCustomRequestClassNamae 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
*/
public function rules()
{
return [
'quantity1' => 'required',
'unit1' => 'required',
'dimension1' => 'required',
'price1' => 'required',
];
}
}
In the controller do something like:
<?php
namespace App\Http\Controllers;
...
use App\Http\Requests\YourCustomRequestClassNamae;
...
class YourControllerName extends Controller
{
...
public function yourMethodName(YourCustomRequestClassNamae $request)
{
$validatedData = $request->validated();
...
If the validation above fails it will return back with a 422 and the messages automatically ready to be pulled from the message bag.
Sources:
https://laravel.com/docs/master/validation#form-request-validation
Example in the wild:
https://github.com/jeremykenedy/larablog/blob/master/app/Http/Requests/StoreTagRequest.php
https://github.com/jeremykenedy/larablog/blob/master/app/Http/Controllers/Admin/TagController.php#L7
https://github.com/jeremykenedy/larablog/blob/master/app/Http/Controllers/Admin/TagController.php#L56

Hw can I get Url params (id for example) in request made by php artisan make:request

I want to create a Request made by php artisan make:request wherein rules I can add a param, for instance I have the following validator in the controller:
$validator = Validator::make($request->all(), [
'title' => 'required|unique:posts|max:{{number}}',
'body' => 'required',
]);
Where number is from url parameter
How can I get this url parameter in my Request class?
Here is my Request class:
<?php
namespace Modules\Blog\Http\Requests;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Http\Exceptions\HttpResponseException;
class SaveBlogCategoriesRequest extends FormRequest
{
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
dd($request->param);
return [
'lang' => 'required',
'name' => 'required',
'slug' => "required|unique:blog_categories_id,slug,", // here I want to add id from param
];
}
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
protected function failedValidation(Validator $validator)
{
$data = [
'status' => false,
'validator' => true,
'msg' => [
'e' => $validator->messages(),
'type' => 'error'
],
];
throw new HttpResponseException(response()->json($data));
}
}
For the request class, you dont need to instantiate the validator
class ModelCreateRequest extends FormRequest
{
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
//if you need the input, you can access it via $this->request;
$param = $this->request->get('param');
//or you can also access it directly (yeah I know it not intuitive)
$param = $this->param
return [
'lang' => 'required',
'name' => 'required',
'slug' => "required|unique:blog_categories_id,slug,".$param,
];
}
}
Use dd($this) to get the request object in request class

How to define field specific error message or overwrite the default one for a custom validation rule used in a FormRequest in Laravel 5.5

I have created a custom validation rule and I am using it to validate a data field in a FormRequest.
However, I would like to use a different message for this field and not the default message that is set in the Rule's message() method.
So, I tried using the method messages() inside of the FormRequest using a key of the field name and the rule (in snake case)
public function rules()
{
return [
'clients' => [
new ClientArrayRule(),
],
];
}
public function messages()
{
return [
'clients.client_array_rule' => "clients should be a valid client array"
];
}
The error message did not change, I investigated a little inside the code of the validator and I found out that for custom rules, it uses the method validateUsingCustomRule that doesn't seem to care about custom messages.
Any ideas on how it can be overwritten or what would be the best way to do it?
For custom message on Laravel:
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'username' => 'required',
'password' => 'required',
'email' => 'required',
'age' => 'required|gte:4',
];
}
/**
* Get the error messages for the defined validation rules.
*
* #return array
*/
public function messages()
{
return [
'username.required' => 'Custom message',
'password.required' => 'Custom message',
'email.required' => 'Custom message',
'age.required' => 'Custom message',
'age.gte' => 'Custom message'
];
}

Laravel Validation Error Message required_if not working

I am validating a form using Laravel 5.2
using validation check required_if for input youtube-embed. validation takes place successfully but the custom error message does not work. Here is the code maybe some one can take a look.
$messages = [
'youtube-embed.required_if' => 'Please paste in your youtube embed code',
];
$this->validate($request, [
'youtube-embed' => 'required_if:youtube,on',
]);
This is the error message that laravel is returning instead of my custom error:
The youtube-embed field is required when youtube is on.
Try this:
$this->validate($request,
['youtube-embed' => 'required_if:youtube,on',],
['required_if' => 'Please paste in your youtube embed code',]
);
Basically you can pass your custom messages as third parameter in validate function.
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
$rules = [
'payout_method' => 'required:in,bankTransfer,paypal',
'paypal_email' => 'required_if:payment_type,paypal|email',
'receiver' => 'required_if:payment_type,bankTransfer|max:45',
'iban' => 'required_if:payment_type,bankTransfer|max:45|iban',
'bic' => 'required_if:payment_type,bankTransfer|max:15|bic',
];
return $rules;
}
/**
* Get the error messages for the defined validation rules.
*
* #return array
*/
public function messages()
{
return [
'payout_method.required' => trans('validation.attributes.payout_type_required'),
'paypal_email.required_if' => trans('validation.attributes.paypal_email_required'),
'paypal_email.email' => trans('validation.attributes.paypal_email_invalid'),
'iban.required_if' => trans('validation.attributes.bank_account_required'),
'bic.required_if' => trans('validation.attributes.bank_swift_required'),
'iban.iban' => trans('validation.attributes.bank_account_invalid'),
'bic.bic' => trans('validation.attributes.bank_swift_invalid'),
];
}
what i can do in this case? Laravel return 'The paypal email field is required.' for other fields this work, only not work with required_if
If your'e using the Request class:
public function messages()
{
return [
'youtube-embed.required' => 'Your custom message here.',
];
}
Works on Laravel 7

Custom error message is not working laravel5.1 form request?

Custom error message in form request class in not working, my form request class given below,
class FileRequest extends Request {
protected $rules = [
'title' => ['required', 'max:125'],
'category_id' => ['required', 'integer', 'exists:file_categories,id']
];
public function authorize() {
return true;
}
public function rules() {
return $this->rules;
}
public function message() {
return [
"category_id.required" => 'Category required',
];
}
}
Here when category_id is null, showing error message category id is required instead of Category required in laravel 5.1?
It is messages, not message.
Change
public function message()
to
public function messages()
You do not need to create any functions to change these messages. In the file /resources/lang/en/validation.php you can add translations for the field names you are using in the attributes array.
In your case, you would do the following:
return [
'attributes' => [
'category_id' => 'Category'
],
];
Now, whenever the category_id doesn't pass the validations, the error message will display this simply as Category.

Categories