Tahmid-ni7
Tahmid-ni7

Reputation: 410

The smart way of set custom validations message in laravel without making a request class

I found difficulties to set custom validation message without making a request class. That's why I am explaining it for a better understanding.

Default validation of laravel:

public function store(Request $request)
    {
        $this->validate($request, [
            'name' => 'required|unique:categories',
        ]);
        $input = $request->all();
        Category::create($input);

        Session::flash('create_category','Category created successfully');
        return redirect('admin/categories');
    }

It will show the default message of laravel. In this question-answer section I will show how easily I solved this problem with the help of laravel documentation. you can find other ways of doing this here in laravel documentation.

Upvotes: 2

Views: 191

Answers (1)

Tahmid-ni7
Tahmid-ni7

Reputation: 410

You have to simply pass the three values to the validate parameter.

  • Your input as $request
  • Your rules as $rules
  • Your custom message as $message

public function store(Request $request)
{
    $rules = ['name'=>'required|unique:categories'];
    $message = [
        'name.required' => 'The category name is required',
        'name.unique'   => 'Category name should be unique'
    ];
    $this->validate($request, $rules, $message);

    $input = $request->all();
    Category::create($input);

    Session::flash('create_category','Category created successfully');
    return redirect('admin/categories');
}

I found that this is the smartest way of doing custom validation without making a request class. If your input field is a few and you want to your validation in the controller then you can do your validation in this way.


Thank's for reading.

Upvotes: 5

Related Questions