79

I'm trying to create customized messages for validation in Laravel 5. Here is what I have tried so far:

$messages = [
    'required'  => 'Harap bagian :attribute di isi.',
    'unique'    => ':attribute sudah digunakan',
];
$validator = Validator::make($request->all(), [
    'username' => array('required','unique:Userlogin,username'),
    'password' => 'required',
    'email'    => array('required','unique:Userlogin,email'),$messages
]);

if ($validator->fails()) { 
    return redirect('/')
        ->withErrors($validator) // send back all errors to the login form
        ->withInput();
} else {
    return redirect('/')
        ->with('status', 'Kami sudah mengirimkan email, silahkan di konfirmasi');   
}   

But it's not working. The message is still the same as the default one. How can I fix this, so that I can use my custom messages?

miken32
  • 42,008
  • 16
  • 111
  • 154
YVS1102
  • 2,658
  • 5
  • 34
  • 63
  • 4
    All these years and nobody pointed out the simple typo. Inside `Validator::make()`, the `$messages` variable was accidentally put inside the rules array. – miken32 Nov 16 '19 at 17:29

13 Answers13

122

Laravel 5.7.*

Also You can try something like this. For me is the easiest way to make custom messages in methods when you want to validate requests:

public function store()
{
    request()->validate([
        'file' => 'required',
        'type' => 'required'
    ],
    [
        'file.required' => 'You have to choose the file!',
        'type.required' => 'You have to choose type of the file!'
    ]);
}
Jankyz
  • 1,427
  • 1
  • 9
  • 8
  • 3
    This was the easiest for me as I was pressed for time and needed to do this in only one place. It is quite handy but if you are going to need custom messages in a number of places, it would be more prudent to have them all in one place. It makes tracking easier and makes the code more legible than if you have custom messages in each validation statement. I upvoted your answer because of my unique usecase and I want to say thank you for it (even though, SO advises against thanks and me too posts, you need to know that you helped me out of a bind and I delivered in time). – Mexen Feb 26 '19 at 10:41
  • Thank You so much @Mexen Im glad that I could help! – Jankyz Mar 01 '19 at 07:57
  • @Geo4you Thanks a lot, it really helped me. – Masood Jun 15 '19 at 17:32
100

If you use $this->validate() simplest one, then you should write code something like this..

$rules = [
        'name' => 'required',
        'email' => 'required|email',
        'message' => 'required|max:250',
    ];

    $customMessages = [
        'required' => 'The :attribute field is required.'
    ];

    $this->validate($request, $rules, $customMessages);
Zedex7
  • 1,624
  • 1
  • 12
  • 21
32

You can provide custom message like :

$rules = array(
            'URL' => 'required|url'
        );    
$messages = array(
                'URL.required' => 'URL is required.'
            );
$validator = Validator::make( $request->all(), $rules, $messages );

if ( $validator->fails() ) 
{
    return [
        'success' => 0, 
        'message' => $validator->errors()->first()
    ];
}

or

The way you have tried, you missed Validator::replacer(), to replace the :variable

Validator::replacer('custom_validation_rule', function($message, $attribute, $rule, $parameters){
    return str_replace(':foo', $parameters[0], $message);
});

You can read more from here and replacer from here

Jigar Shah
  • 6,143
  • 2
  • 28
  • 41
31

For Laravel 8.x, 7.x, 6.x
With the custom rule defined, you might use it in your controller validation like so :

$validatedData = $request->validate([
       'f_name' => 'required|min:8',
       'l_name' => 'required',
   ],
   [
    'f_name.required'=> 'Your First Name is Required', // custom message
    'f_name.min'=> 'First Name Should be Minimum of 8 Character', // custom message
    'l_name.required'=> 'Your Last Name is Required' // custom message
   ]
);

For localization you can use :

['f_name.required'=> trans('user.your first name is required'],

Hope this helps...

STA
  • 30,729
  • 8
  • 45
  • 59
11
$rules = [
  'username' => 'required,unique:Userlogin,username',
  'password' => 'required',
  'email'    => 'required,unique:Userlogin,email'
];

$messages = [
  'required'  => 'The :attribute field is required.',
  'unique'    => ':attribute is already used'
];

$request->validate($rules,$messages);
//only if validation success code below will be executed
muzudre
  • 7
  • 5
pgrono
  • 740
  • 7
  • 5
  • This is the same as [a previous answer](https://stackoverflow.com/a/53573460/1255289) posted a year ago. – miken32 Nov 16 '19 at 17:21
7
//Here is the shortest way of doing it.
 $request->validate([
     'username' => 'required|unique:Userlogin,username',
     'password' => 'required',
     'email'    => 'required|unique:Userlogin,email'
 ],
 [
     'required'  => 'The :attribute field is required.',
     'unique'    => ':attribute is already used'
 ]);
//The code below will be executed only if validation is correct.
Kaleem Shoukat
  • 811
  • 6
  • 14
7

run below command to create a custom rule on Laravel
ı assuming that name is CustomRule

php artisan make:rule CustomRule

and as a result, the command was created such as PHP code

if required keyword hasn't on Rules,That rule will not work

<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;

class CustomRule implements Rule
{
    /**
     * Create a new rule instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        //return  true or false
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return 'The validation error message.';
    }
}


and came time using that first, we should create a request class if we have not

php artisan make:request CustomRequest

CustomRequest.php

<?php


namespace App\Http\Requests\Payment;

use App\Rules\CustomRule;
use Illuminate\Foundation\Http\FormRequest;

class CustomRequest extends FormRequest
{


    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules(): array
    {
        return [
            'custom' => ['required', new CustomRule()],
        ];
    }

    /**
     * @return array|string[]
     */
    public function messages(): array
    {
        return [
            'custom.required' => ':attribute can not be empty.',
        ];
    }
}

and on your controller, you should inject custom requests to the controller

your controller method

class FooController
{
    public function bar(CustomRequest $request)
    {
        
    }
}

dılo sürücü
  • 3,821
  • 1
  • 26
  • 28
6

In the case you are using Request as a separate file:

 public function rules()
 {
    return [
        'preparation_method' => 'required|string',
    ];
 }

public function messages()
{
    return [
        'preparation_method.required' => 'Description is required',
    ];
}

Tested out in Laravel 6+

Larstton
  • 138
  • 1
  • 9
5
    $rules = [
        'name' => 'required',
        'email' => 'required|email',
        'message' => 'required|max:250',
    ];

    $customMessages = [
        'required' => 'The :attribute field is required.',
        'max' => 'The :attribute field is may not be greater than :max.'
    ];

    $this->validate($request, $rules, $customMessages);
SK Toke
  • 314
  • 1
  • 3
  • 7
4

You can also use the methods setAttributeNames() and setCustomMessages(), like this:

$validation = Validator::make($this->input, static::$rules);

$attributeNames = array(
    'email' => 'E-mail',
    'password' => 'Password'
);

$messages = [
    'email.exists' => 'No user was found with this e-mail address'
];

$validation->setAttributeNames($attributeNames);
$validation->setCustomMessages($messages);
Gleb Kemarsky
  • 10,160
  • 7
  • 43
  • 68
Bruno
  • 91
  • 1
  • 3
  • 1
    I really like this method. It's great when used with an after hook on a FormRequest, eg. https://laravel.com/docs/8.x/validation#adding-after-hooks-to-form-requests – Joel Mellon Jan 30 '22 at 00:43
4

For those who didn't get this issue resolve (tested on Laravel 8.x):

$validated = Validator::make($request->all(),[
   'code' => 'required|numeric'
  ],
  [
    'code.required'=> 'Code is Required', // custom message
    'code.numeric'=> 'Code must be Number', // custom message       
   ]
);

//Check the validation
if ($validated->fails())
{        
    return $validated->errors();
}
vahid sabet
  • 485
  • 1
  • 6
  • 16
0

you can customise the message for different scenarios based on the request.

Just return a different message with a conditional.


<?php

namespace App\Rules;

use App\Helpers\QueryBuilderHelper;
use App\Models\Product;
use Illuminate\Contracts\Validation\Rule;

class ProductIsUnique implements Rule
{

    private array $attributes;
    private bool $hasAttributes;

    /**
     * Create a new rule instance.
     *
     * @return void
     */
    public function __construct(array $attributes)
    {
        $this->attributes = $attributes;
        $this->hasAttributes = true;
    }

    /**
     * Determine if the validation rule passes.
     *
     * @param string $attribute
     * @param mixed $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        $brandAttributeOptions = collect($this->attributes['relationships']['brand-attribute-options']['data'])->pluck('id');

        $query = Product::query();

        $query->when($brandAttributeOptions->isEmpty(), function ($query) use ($value) {
            $query->where('name', $value);
            $this->hasAttributes = false;
        });

        
        return !$query->exists();
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return ($this->hasAttributes) ? 'The Selected attributes & Product Name are not unique' : 'Product Name is not unique';
    }
}

mikoop
  • 1,981
  • 1
  • 18
  • 18
0

Laravel 10.x

If you are using Form Requests, add another method called messages(): array in your request.

class YourRequest extends FormRequest
{

    public function rules(): array
    {
        return [
            'name' => 'required',
            'email' => 'required|email',
            ...
        ];
    }

    //Add the following method

    public function messages(): array
    {
        return [
            'email.required' => 'Custom message for Email Required',
        ];
    }
}

Then the message will be displayed automatically once the request is send from the form.

Sabin Chacko
  • 713
  • 6
  • 17