本文實例講述了laravel框架中表單請求類型和CSRF防護。分享給大家供大家參考,具體如下:
laravel中為我們提供了綁定不同http請求類型的函數。
Route::get('/test', function () {});
Route::post('/test', function () {});
Route::put('/test', function () {});
Route::patch('/test', function () {});
Route::delete('/test', function () {});
Route::options('/test', function () {});
但有些時候,我們通過創建資源控制器,里面的 update() 方法綁定的是 PUT 類型的http請求。
這就需要我們通過表單提交模擬PUT請求。我們可以自已添加一個 _method 的隱藏字段,值為 PUT。
form action="{{ route('test') }}" method="post">
input type="hidden" name="_method" value="PUT">
用戶名:input type="text" name="name">
密碼:input type="password" name="pwd">
input type="submit" value="提交">
/form>
也可以使用laravel為我們提供的 method_field() 方法。
form action="{{ route('test') }}" method="post">
{{ method_field('PUT') }}
用戶名:input type="text" name="name">
密碼:input type="password" name="pwd">
input type="submit" value="提交">
/form>
laravel默認會對每個提交請求,進行csrf令牌的驗證。為了通過驗證,需要在表單中添加 _token 隱藏字段。
form action="{{ route('test') }}" method="post">
input type="hidden" name="_token" value="{{ csrf_token() }}">
用戶名:input type="text" name="name">
密碼:input type="password" name="pwd">
input type="submit" value="提交">
/form>
或者使用 csrf_field() 方法。
form action="{{ route('test') }}" method="post">
{{ csrf_field() }}
用戶名:input type="text" name="name">
密碼:input type="password" name="pwd">
input type="submit" value="提交">
/form>
更多關于Laravel相關內容感興趣的讀者可查看本站專題:《Laravel框架入門與進階教程》、《php優秀開發框架總結》、《php面向對象程序設計入門教程》、《php+mysql數據庫操作入門教程》及《php常見數據庫操作技巧匯總》
希望本文所述對大家基于Laravel框架的PHP程序設計有所幫助。
您可能感興趣的文章:- Laravel 解決419錯誤 -ajax請求錯誤的問題(CSRF驗證)
- 對laravel的csrf 防御機制詳解,及form中csrf_token()的存在介紹
- laravel 實現關閉CSRF(全部關閉、部分關閉)
- laravel csrf排除路由,禁止,關閉指定路由的例子
- Laravel框架中VerifyCsrfToken報錯問題的解決
- laravel csrf驗證總結