【问题标题】:Laravel - Request safe method does not existLaravel - 请求安全方法不存在
【发布时间】:2021-10-25 12:36:54
【问题描述】:

我使用 artisan make 命令生成了我的 StorePostRequest。
我在规则方法上定义了规则:

public function rules()
{
    return [
        'title' => 'required|min:3|max:255',
        'slug' => ['required', Rule::unique('posts', 'slug')],
        'thumbnail' =>'required|image',
        'excerpt' => 'required|min:3',
        'body' => 'required|min:3',
        'category_id' => 'required|exists:categories,id'
    ];
}

但是,在我的 PostController 中,除了 thumbnail 之外,我无法使用 safe()->except('thumbnail') 获得经过验证的输入,就像 here 解释的那样

我收到了错误

BadMethodCallException
Method App\Http\Requests\StorePostRequest::safe does not exist.

【问题讨论】:

  • $validated = $request->safe()->except(['thumbnail'])
  • 感谢您的回复。但是,$request->safe()->except(['thumbnail']) 也不起作用
  • 您可以使用only() 获取一些指定的输入 `$validated = $request->only(['// all keys you need']);
  • 感谢您的帮助,$request->except('thumbnail') 工作。
  • @Nel 警告词如果你使用 $request->except() 你会得到所有的请求字段,即使是那些没有通过验证的字段!

标签: laravel laravel-8 laravel-request


【解决方案1】:

通过运行检查你的 laravel/framework 版本

php artisan --version

FormRequest 类was only added in version8.55.0 上的安全方法。

请记住,仅仅因为您使用的是 laravel 框架的 a 版本 8,这并不意味着您将拥有 laravel 8.x 中的所有方法和属性文档。当然,除非您使用的是当前最新版本 8。

【讨论】:

    【解决方案2】:

    直接在$request 上使用except() 方法有效。感谢@JEJ 的帮助。

    $request->except('thumbnail');
    

    【讨论】:

      猜你喜欢
      • 2018-08-26
      • 1970-01-01
      • 2016-10-21
      • 2018-08-13
      • 1970-01-01
      • 1970-01-01
      • 2019-04-20
      • 2016-10-06
      • 2017-11-07
      相关资源
      最近更新 更多