Laravel添加数据库数据时出现ArgumentCountError错误求助
解决Laravel分类添加时的ArgumentCountError错误
错误详情
ArgumentCountError
调用App\Http\Requests\Admin\Categories\StoreRequest::Illuminate\Foundation\Providers{closure}()时传入参数数量不足,预期传入1个参数但实际传入0个,错误发生在E:\xampp\htdocs\cylinders\cylinders\vendor\laravel\framework\src\Illuminate\Macroable\Traits\Macroable.php第124行。
问题根源
错误出在控制器的store方法中:
public function store(StoreRequest $request) { $validatedData = $request->validate(); // 此处是问题核心 $createdCategory = Category::create([ 'title' => $validatedData['title'], 'slug' => $validatedData['slug'], ]); if(!$createdCategory){ return back()->with('failed', 'Failed to Create Category.'); } return back()->with('success', 'Success to Create Category.'); }
当使用自定义FormRequest(即这里的StoreRequest)时,Laravel会自动在进入控制器方法前完成验证流程,无需手动调用$request->validate()。而validate()方法本身要求传入验证规则数组作为参数,你此处未传参,直接触发了参数不足的错误。
解决方案
删除多余的$request->validate()调用,改用$request->validated()获取经过验证的请求数据,修改后的控制器代码如下:
public function store(StoreRequest $request) { $validatedData = $request->validated(); $createdCategory = Category::create([ 'title' => $validatedData['title'], 'slug' => $validatedData['slug'], ]); if(!$createdCategory){ return back()->with('failed', 'Failed to Create Category.'); } return back()->with('success', 'Success to Create Category.'); }
也可以简化为更紧凑的写法:
public function store(StoreRequest $request) { $createdCategory = Category::create($request->validated()); return back()->with( $createdCategory ? 'success' : 'failed', $createdCategory ? 'Success to Create Category.' : 'Failed to Create Category.' ); }
其他代码验证
你的路由、表单和StoreRequest验证类均无问题,无需修改:
路由
Route::post('', [CategoriesController::class, 'store'])->name('admin.categories.store');
页面表单
<form action="{{ route('admin.categories.store') }}" method="post"> @csrf <div class="card-body"> <div class="row"> <div class="col-md-6"> <div class="form-group"> <label>Slug</label> <input type="text" class="form-control" name="slug"> </div> </div> <div class="col-md-6"> <div class="form-group"> <label>Title</label> <input type="text" class="form-control" name="title"> </div> </div> </div> </div> <!-- /.card-body --> <div class="card-footer"> <button type="submit" class="btn btn-primary float-left">Save</button> </div> </form>
请求验证类
<?php namespace App\Http\Requests\Admin\Categories; use Illuminate\Foundation\Http\FormRequest; 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 [ 'title' => 'required|min:3|max:128|unique:categories,title', 'slug' => 'required|min:3|max:128|unique:categories,slug', ]; } }
内容的提问来源于stack exchange,提问作者amir garmroudi
相关产品推荐
相关产品推荐

