Laravel 7自定义表单请求验证失效,请求数据无法获取
问题
使用Laravel 7框架时,自定义的StoreRequest表单请求类出现以下异常:
required验证规则完全不生效,请求返回无任何错误提示- 调用
dd($request->all())无法获取请求数据 - 改用
Illuminate\Http\Request类后,能正常获取请求数据,但不会执行验证逻辑
相关代码如下:
控制器方法
public function store(StoreRequest $request) { dd($request->all()); if (!auth()->user()->can('add-users')) { abort(401); } try { $userStatus = app(CreateUser::class)->execute($request->all()); if ($userStatus == true) { return redirect()->back()->with('success', 'User successfully created.'); } else { return redirect()->back()->with('error', 'Oops Something went wrong!'); } } catch (\Exception $ex) { return redirect()->back()->with('error', $ex->getMessage()); } }
请求类代码
class StoreRequest 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 [ 'name' => ['required','string','max:255'], 'email' => ['required','string','max:255'], 'password' => 'required', 'organization_id' => 'required' ]; } }
原因及解决方法
请求类命名空间与引入错误
检查StoreRequest的命名空间是否正确,默认表单请求类应放在App\Http\Requests目录下,类顶部需声明:namespace App\Http\Requests;同时控制器内要正确引入该类:
use App\Http\Requests\StoreRequest;命名空间错误会导致Laravel无法识别自定义请求类,引发请求数据异常且跳过验证。
CSRF令牌验证失败
表单请求类会自动验证CSRF令牌,若前端未携带_token字段,验证会静默失败,导致请求数据无法正常解析。
解决:在Blade表单中添加@csrf指令,AJAX请求则携带X-CSRF-TOKEN请求头。请求内容类型不匹配
若为AJAX请求且发送的是application/json格式数据,表单请求类默认无法解析,需在请求类中添加方法手动处理:protected function prepareForValidation() { if ($this->isJson()) { $this->merge(json_decode($this->getContent(), true)); } }错误信息未正确渲染
Laravel验证失败后会自动携带错误信息返回,但需在前端模板中手动渲染:@if ($errors->any()) <div class="alert alert-danger"> <ul> @foreach ($errors->all() as $error) <li>{{ $error }}</li> @endforeach </ul> </div> @endif缓存或自动加载异常
执行以下命令清除缓存并重新生成自动加载文件:php artisan cache:clear php artisan config:clear composer dump-autoload类自动加载缓存可能导致新创建的请求类无法被Laravel识别。
内容的提问来源于stack exchange,提问作者Uzair Ahmed
相关产品推荐
相关产品推荐

