简体   繁体   English

在 laravel 中设置自定义验证消息的智能方法,无需发出请求 class

[英]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.我发现很难在不发出请求 class 的情况下设置自定义验证消息。 That's why I am explaining it for a better understanding.这就是为什么我解释它以便更好地理解。

Default validation of laravel: 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.它将显示 laravel 的默认消息。 In this question-answer section I will show how easily I solved this problem with the help of laravel documentation.在这个问答部分中,我将展示在 laravel 文档的帮助下解决这个问题是多么容易。 you can find other ways of doing this here inlaravel documentation.您可以在laravel 文档中找到其他方法。

You have to simply pass the three values to the validate parameter.您只需将三个值传递给validate参数。

  • Your input as $request您作为$request的输入
  • Your rules as $rules您的规则为$rules
  • Your custom message as $message您的自定义消息为$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.我发现这是在不发出请求 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.如果您的输入字段很少,并且您想在 controller 中进行验证,那么您可以通过这种方式进行验证。


Thank's for reading.谢谢阅读。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM