【问题标题】:Get model instance in custom request Laravel在自定义请求 Laravel 中获取模型实例
【发布时间】:2019-08-09 21:49:27
【问题描述】:

我有一个带有自定义验证规则的模型,在每个模型中我都有变量 $rules:

public static $rules = [...];

https://medium.com/@konafets/a-better-place-for-your-validation-rules-in-laravel-f5e3f5b7cc

我想在自定义请求中使用这些规则:

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Facades\Auth;

class ModelRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return Auth::check() ? true : false;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return static::$rules;  
    }
}

我得到错误:

Access to undeclared static property: App\Http\Requests\ModelRequest::$rules

在控制器中:

public function store(ModelRequest $request)
{
    ...
}

这是全球性的。我需要获取模型实例,但是如何获取?

【问题讨论】:

  • 你在哪个类中定义了静态$rules属性?
  • 你在哪里定义了这个$rules属性?
  • @Jerodev 在模型中
  • 哪个型号,因为它似乎不在ModelRequest 类中。
  • @mega6382 在模型中。请查看更新后的问题

标签: php laravel


【解决方案1】:

如果您已将 $rules 变量放入模型中,则无法像这样访问它,因为 static 指的是您当前所在的类。 试试这个:

注意:我假设您的模型位于 App 命名空间

   // In your model class
   class YourModel extends Model{

     const RULES=[];

   }

   //Then in your request class
  class ModelRequest extends FormRequest 
  {
    public function rules()
    {
      return App\YourModel::RULES;  
    }
  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-09
    • 2016-09-17
    • 2019-09-15
    相关资源
    最近更新 更多