[英]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.