lk404
lk404

Reputation: 334

how to give custom validation messages in laravel 5

I'v been following on laravel 4.2 and to day tried laravel 5.

how can you add custom validation messages to rules in laravel 5.

Code Sample

namespace App\Http\Requests;

 
use App\Http\Requests\Request;
 

class MyRequest extends Request {


    /**

     * 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 [

            'email' => 'required|email',

            'password' => 'required|min:8'

        ];

    }

}
// in your controller action
public function postLogin(\App\Http\Requests\MyRequest $request)

{

    // code here will not fire

    // if the validation rules

    // in the request fail

}

?>

it's not clear as in 4.2

Upvotes: 2

Views: 4575

Answers (2)

Joe
Joe

Reputation: 4738

As well as the messages() method you can also do this in the lang file (resources/lang/[language]/validation.php) if all you want to do is change, for example the message for a unique rule on an email field across the entire app you can do:

/*
|--------------------------------------------------------------------------
| Custom Validation Language Lines
|--------------------------------------------------------------------------
|
| Here you may specify custom validation messages for attributes using the
| convention "attribute.rule" to name the lines. This makes it quick to
| specify a specific custom language line for a given attribute rule.
|
*/

'custom' => [
    'attribute-name' => [
        'rule-name' => 'custom-message',
    ],
    'email' => [
        'unique' => 'This email is already registered...etc',
    ]
],

Upvotes: 6

lukasgeiter
lukasgeiter

Reputation: 153150

You can return them from the messages() method like you do with rules¨:

public function messages(){
    return [
        'required' => 'The :attribute field is required.'
    ];
}

Upvotes: 3

Related Questions