Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Customize Validation Messages in Laravel Requests

How do i customize my Validation Messages in My REQUESTS FILE?

how do i add messages next to the rules? What i want is to put customized messages just like the common validation. Is it possible? to do just the normal way of validation in the Requests?

<?php

namespace App\Http\Requests;

use App\Http\Requests\Request;

class ArticleRequest 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 [
        'title' => 'required|min:5',
        'content' =>'required',
        'user_id' => 'required|numeric',
        'category_id' => 'required|numeric',
        'published_at' => 'required|date'
        ];
    }

}

like image 472
Fluxify Avatar asked Sep 05 '16 09:09

Fluxify


2 Answers

You can define a messages() method with validation rules for that form request only:

class StoreArticleRequest extends Request
{
    //

    public function messages()
    {
        return [
            'title.required' => 'The title is required.',
            'category_id.numeric' => 'Invalid category value.',
        ];
    }
}

It takes the form of the field name and the rule name, with a dot in between, i.e. field.rule.

like image 96
Martin Bean Avatar answered Oct 09 '22 03:10

Martin Bean


You may customize the error messages used by the form request by overriding the messages method. This method should return an array of attribute / rule pairs and their corresponding error messages:

public function messages()
{
    return [
        'title.required' => 'A title is required',
        'body.required'  => 'A message is required',
    ];
}

https://laravel.com/docs/5.3/validation#customizing-the-error-messages

like image 45
Alexey Mezenin Avatar answered Oct 09 '22 05:10

Alexey Mezenin