Table of Contents
修改提示信息变为中文
Home Backend Development PHP Tutorial Laravel 五 基础(十一)- 表单验证

Laravel 五 基础(十一)- 表单验证

Jun 13, 2016 pm 12:17 PM
gt quot request

Laravel 5 基础(十一)- 表单验证

在建立一个文章的时候,如果你什么都不输入直接提交,ok,你获得了一个空的文章,没有任何错误提示,这是不对的。在命令行下运行 php artisan 可以看到一个选项 make:request,新建一个form request类。在命令行执行

1

<code>php artisan make:request CreateArticleRequest</code>

Copy after login

生成的文件在 app/http/requests 目录下。在文件中我们可以看到两个方法:

1

<code>    public function authorize() {       return false;   }       public function rules() {       return [            //      ];  }</code>

Copy after login

authorize 表示用户在提交表单的时候是否需要是认证用户,我们不需要认证,返回 true。rules是我们的规则方法。让我们修改这个方法:

1

<code>    public function authorize() {       //修改为 true,表示不需要认证,或者是通过认证      return true;    }       public function rules() {       return [            &#39;title&#39; => &#39;required|min:3&#39;,        &#39;body&#39; => &#39;required&#39;,        &#39;published_at&#39; => &#39;required|date&#39;     ];  }</code>

Copy after login

其他的约束可以插看 laravel 的文档。上面的约束表示 title 是必须输入的,最少3个字符,body 是必须的,published_at 是必须的而且是日期。

在视图中,我们总是可以访问 $errors 变量来判断我们是否有错误,修改视图

1

<code>    @if ($errors->any())        <ul class="alert alert-danger">            @foreach($errors->all() as $error)                <li>{{ $error }}</li>            @endforeach        </ul>    @endif        {{--使用我们添加的 illuminate\html 开源库--}}    {!! Form::open([&#39;url&#39; => &#39;articles&#39;]) !!}</code>

Copy after login

修改控制器,引入我们的 Request 类。

1

<code>    public function store(Requests\CreateArticleRequest $request) {        Article::create($request->all());        return redirect(&#39;articles&#39;);    }</code>

Copy after login

再次提交表单,什么都不填,可以看到错误信息。

修改提示信息变为中文

显示的是英文的错误信息,实际上laravel考虑到了国际化的问题,首先修改 config/app.php

1

<code>    &#39;locale&#39; => &#39;zh&#39;,</code>

Copy after login

将 locale 语言设置为中文,然后再 resources/lang 下面新建文件夹 zh, 拷贝 resources/lang/en/validation.php 文件到 zh 目录下,修改:

1

<code>    "min"                  => [      "numeric" => "The :attribute must be at least :min.",        "file"    => "The :attribute must be at least :min kilobytes.",      "string"  => ":attribute 至少要包含 :min 字符。",        "array"   => "The :attribute must have at least :min items.",    ],      "required"             => ":attribute 必须填写。",</code>

Copy after login

其他的可以自行翻译。再次提交空表单,错误信息为中文了。而且 min:3 的判断也为最少3个中文。

--

laravel 也在控制器中集成了 validate 方法,换句话说,我们不一定要生成 request 类,这些工作我们可以直接在控制器中完成。

修改控制器:

1

<code>     //注意 Request 的命名空间,不要弄错了    public function store(\Illuminate\Http\Request $request) {        $this->validate($request, [            &#39;title&#39; => &#39;required|min:3&#39;,            &#39;body&#39; => &#39;required&#39;,            &#39;published_at&#39; => &#39;required|date&#39;        ]);        Article::create($request->all());        return redirect(&#39;articles&#39;);    }</code>

Copy after login

结果相同,这样可以更快速的完成简单的验证。

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What are the differences between Huawei GT3 Pro and GT4? What are the differences between Huawei GT3 Pro and GT4? Dec 29, 2023 pm 02:27 PM

Many users will choose the Huawei brand when choosing smart watches. Among them, Huawei GT3pro and GT4 are very popular choices. Many users are curious about the difference between Huawei GT3pro and GT4. Let’s introduce the two to you. . What are the differences between Huawei GT3pro and GT4? 1. Appearance GT4: 46mm and 41mm, the material is glass mirror + stainless steel body + high-resolution fiber back shell. GT3pro: 46.6mm and 42.9mm, the material is sapphire glass + titanium body/ceramic body + ceramic back shell 2. Healthy GT4: Using the latest Huawei Truseen5.5+ algorithm, the results will be more accurate. GT3pro: Added ECG electrocardiogram and blood vessel and safety

What does php request mean? What does php request mean? Jul 07, 2021 pm 01:49 PM

The Chinese meaning of request is "request". It is a global variable in PHP and is an array containing "$_POST", "$_GET" and "$_COOKIE". The "$_REQUEST" variable can obtain data and COOKIE information submitted by POST or GET.

Fix: Snipping tool not working in Windows 11 Fix: Snipping tool not working in Windows 11 Aug 24, 2023 am 09:48 AM

Why Snipping Tool Not Working on Windows 11 Understanding the root cause of the problem can help find the right solution. Here are the top reasons why the Snipping Tool might not be working properly: Focus Assistant is On: This prevents the Snipping Tool from opening. Corrupted application: If the snipping tool crashes on launch, it might be corrupted. Outdated graphics drivers: Incompatible drivers may interfere with the snipping tool. Interference from other applications: Other running applications may conflict with the Snipping Tool. Certificate has expired: An error during the upgrade process may cause this issu simple solution. These are suitable for most users and do not require any special technical knowledge. 1. Update Windows and Microsoft Store apps

How to use the urllib.request.urlopen() function to send a GET request in Python 3.x How to use the urllib.request.urlopen() function to send a GET request in Python 3.x Jul 30, 2023 am 11:28 AM

How to use the urllib.request.urlopen() function in Python3.x to send a GET request. In network programming, we often need to obtain data from a remote server by sending an HTTP request. In Python, we can use the urllib.request.urlopen() function in the urllib module to send an HTTP request and get the response returned by the server. This article will introduce how to use

How to encapsulate Vue3 Axios interceptor into request file How to encapsulate Vue3 Axios interceptor into request file May 19, 2023 am 11:49 AM

1. Create a new file called request.js and import Axios: importaxiosfrom'axios'; 2. Create a function called request and export it: This will create a function called request and export it Set up a new Axios instance with a base URL. To add timeout settings in a wrapped Axios instance, you can pass the timeout option when creating the Axios instance. exportconstrequest=axios.create({baseURL:'https://example.

What is request in PHP What is request in PHP Jun 01, 2023 am 10:12 AM

Request in PHP refers to request. It is a super global variable in PHP. It is used to collect data submitted by HTML forms and parameters in URLs. It can obtain data from GET and POST requests at the same time. Note that $_request is an associative array. , where the keys are the names of the form fields and the values ​​are the values ​​of the form fields. When using the $_request variable, user-entered data should always be validated and filtered to avoid security issues.

What is the Request object in PHP? What is the Request object in PHP? Feb 27, 2024 pm 09:06 PM

The Request object in PHP is an object used to handle HTTP requests sent by the client to the server. Through the Request object, we can obtain the client's request information, such as request method, request header information, request parameters, etc., so as to process and respond to the request. In PHP, you can use global variables such as $_REQUEST, $_GET, $_POST, etc. to obtain requested information, but these variables are not objects, but arrays. In order to process request information more flexibly and conveniently, you can

How to Fix Can't Connect to App Store Error on iPhone How to Fix Can't Connect to App Store Error on iPhone Jul 29, 2023 am 08:22 AM

Part 1: Initial Troubleshooting Steps Checking Apple’s System Status: Before delving into complex solutions, let’s start with the basics. The problem may not lie with your device; Apple's servers may be down. Visit Apple's System Status page to see if the AppStore is working properly. If there's a problem, all you can do is wait for Apple to fix it. Check your internet connection: Make sure you have a stable internet connection as the "Unable to connect to AppStore" issue can sometimes be attributed to a poor connection. Try switching between Wi-Fi and mobile data or resetting network settings (General > Reset > Reset Network Settings > Settings). Update your iOS version:

See all articles