使用request的方式
<code>E:<span>\Laravel</span><span>\blog</span>>php artisan make:request ArticleRequest</code>
在app/http/request下產生ArticleRequest.php修改如下
<code><?php namespace App\Http\Requests; use App\Http\Requests\Request; <span><span>class</span><span>ArticleRequest</span><span>extends</span><span>Request</span></span> { <span>/** * Determine if the user is authorized to make this request. * * <span>@return</span> bool */</span> public function authorize() { <span>return</span><span>true</span>; } <span>/** * Get the validation rules that apply to the request. * * <span>@return</span> array */</span> public function rules() { <span>return</span> [ <span>//</span><span>"name"</span>=><span>"<strong>require</strong>d"</span>, ]; } } </code>
rules 為驗證規則
authorize 要回傳true
<code>{<span>!</span><span>!</span><span>Form</span>::<span>open</span>([<span>"url"</span>=><span>"/site/store"</span>]) <span>!</span><span>!</span>} {<span>!</span><span>!</span><span>Form</span>::<span>text</span>(<span>"name"</span>,<span>"aa"</span>,[<span>"class"</span>=><span>"form-controller"</span>,<span>"id"</span>=><span>"t"</span>]) <span>!</span><span>!</span>} {<span>!</span><span>!</span><span>Form</span>::<span>submit</span>() <span>!</span><span>!</span>} {<span>!</span><span>!</span><span>Form</span>::<span>close</span>() <span>!</span><span>!</span>} {{--{{$<span>errors</span>}}--}} {{--{<span>!</span><span>!</span> $<span>errors</span><span>!</span><span>!</span>}--}} //用于显示验证不通过的错误信息 @<span>if</span>($<span>errors</span><span>-></span><span>any</span>()) @<span>foreach</span>($<span>errors</span><span>-></span><span>all</span>() <span>as</span> $<span>err</span>) {<span>!</span><span>!</span> $<span>err</span><span>!</span><span>!</span>} @<span>endforeach</span> @<span>endif</span></code>
控制器只需要RequestsArticleRequest 參數類型用上面的request即可
<code><span>public</span><span><span>function</span><span>store</span><span>(Requests\ArticleRequest <span>$req</span>)</span>{</span> dd(<span>"fdsaf"</span>); }</code>
驗證通過後執行方法,不透過重定向表單頁面
使用validate的方式
控制器參數正常的
validate 第二個參數與上面的rules相同
<code><span>public</span><span><span>function</span><span>store</span><span>(Request <span>$req</span>)</span>{</span><span>$this</span>->validate(<span>$req</span>,[<span>"name"</span>=><span>"<strong>require</strong>d"</span>]); dd(<span>"fdsaf"</span>); }</code>
<code><span>'locale'</span> => <span>'zh'</span>,</code>
zh
對應著修改成中文
如欄位必面修改
resources/lang/zh/validation.php中的
<code><span>'<strong>require</strong>d'</span> => <span>'The :attribute field 必须.'</span>,</code>
以上就介紹了laravel 表單驗讓,包含了require方面的內容,希望對PHP教學有興趣的朋友有幫助。