【问题标题】:Laravel unique validation with Route parameterLaravel 使用 Route 参数进行唯一验证
【发布时间】:2016-08-01 18:24:55
【问题描述】:

我是 PHP 新手,所以现在我需要使用静态变量验证模型。

这就是我所拥有的

class Setting extends Model {

    protected $table = 'settings';

    public static $rules = [
        'skey' => 'required|unique:table,id,' . Route::input('settings')
    ];
}

它抛出以下错误:语法错误,意外'.',期待']'

好的,我知道不能用于声明变量。

现在,这是我的问题:

  • 如何使用 Illuminate\Http\Request 完成此操作,我不想创建一个更容易使用的新 SettingRequest。
  • 我也不想在控制器中使用存储或更新方法。我想在两种方法创建/更新中都使用这种方式。
  • 在 PHP 中,无论如何都要将 setter 或 getter 创建为 C#。

【问题讨论】:

  • 如果你打印 Route::get('settings') 你会得到什么?
  • 返回路由参数。例如:/settings/5 => 5
  • 我怀疑Route::get('settings') 给你“5”...试试Request::input('settings')
  • 我以前试过。结果相同。

标签: validation laravel unique getter


【解决方案1】:

你不能像 Luis 说的那样做。

我假设您使用的是 L5。更好的做法是使用 Request 类。

<?php 
    namespace App\Http\Requests;

    class SettingRequest extends Request
    {
        /**
         * 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 [
                'skey' => 'required|unique:table,id,' .$this->input('settings')
            ];
        }
    }

之后,您可以像这样在控制器中使用 SettingRequest 类作为方法参数:

public function update(SettingRequest $request) {}
public function create(SettingRequest $request) {}

【讨论】:

  • 嗨,我在上面的帖子中说过,假设我不想要它,无论如何在 php 中制作 getter 或 setter 而不创建新的 Request 类或用作函数(getRules())?
【解决方案2】:

在那种情况下你不能这样做。尝试在方法中执行此操作:

public static function getRules()
{
    return  [
            'skey' => 'required|unique:table,id,' . Route::input('settings')
    ];
}

【讨论】:

    猜你喜欢
    • 2022-01-12
    • 1970-01-01
    • 2016-04-15
    • 1970-01-01
    • 2018-05-18
    • 2018-07-29
    • 1970-01-01
    • 2022-12-05
    • 2015-02-03
    相关资源
    最近更新 更多