[英]Laravel 5.4 Validation Using Form Requests
我想使用表單請求來驗證模型,所以我首先創建php artisan make:request TaskRequest
,然后在TaskRequest類中添加`
public function rules()
{
return [
'name' => 'required|min:5',
];
}
public function messages()
{
return [
'name.required' => 'A title is required',
];
}
`
按照我的邏輯
Route::post('/tasks',function (\App\Http\Requests\TaskRequest $request){
$task = new \App\Task();
$task->name = $request->input("name");
$task->save();
return response()->json(['task was created',$task], http_response_code());
});
因此,當我嘗試添加任務時,出現錯誤HttpException, This action is unauthorized.,AuthorizationException ...
沒有驗證,對我來說這是工作。 那么我該如何解決這個問題呢?
每個(自行創建的)請求都有一個authorize
功能,該功能確定是否允許用戶發送請求。 這對於檢查管理員權限或類似權限很有用。
在這種情況下,您可以簡單地返回true
。 可以在相應的文檔中找到更多信息
您的TaskRequest
authorize函數如下所示:
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
在您的“表單請求”的自定義請求類中,該類包含驗證邏輯並通過return:true;
而不是return:false;
然后它將像魅力一樣工作。
該代碼將如下所示,
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class portfolioValidate extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'title'=> 'required',
'content'=> 'required'
];
}
}
因為您可以使用中間件對包含此表單的頁面進行身份驗證...,所以我們在FormRequest
類中不需要該授權。 因此,返回true將使其在所有情況下均得到授權。
我認為現在每個人現在都很清楚。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.