Laravel 5.4 表单请求唯一验证: how to access id?

标签 laravel validation laravel-5 request unique

我有以下表单请求:

<?php

namespace App\Http\Requests;

use App\Sociallink;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

class SociallinkRequest 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 [
          'seq' => 'required|unique:sociallinks,seq,' . $this->id . ',id',
          'social_name' => 'required|unique:sociallinks,social_name,' . $this->id . ',id',
          'cssclass' => 'required',
          'url' => 'nullable|active_url'
        ];
    }

我需要字段 seqsocial_name 是唯一的。当我尝试编辑时,此代码不起作用。我发现 dd($this) 中不存在 $this->id。我的网址是:http://prj.test/sociallink/2/edit。这里的许多示例都使用 $this->id 但我无法在代码中的任何位置访问该变量,因为它似乎不存在。当我将 $this->id 替换为物理 id(如本示例中的 2)时,验证工作正常。但动态地,如何使用当前行的 id 进行唯一验证?

最佳答案

除非您有一个带有 id 的表单输入,否则它实际上并不在 $request 中(请求代码中的 $this) 。您可以通过从 Controller 返回整个请求来验证这一点:

return request()->all(); 

假设您定义了如下路由:

sociallink/{sociallink}/edit ...

然后在您的请求中您可以执行以下操作:

public function rules()
{
    $sociallink = $this->route('sociallink');
    return [
      'seq'         => 'required|unique:sociallinks,seq,' . $sociallink . ',id',
      'social_name' => 'required|unique:sociallinks,social_name,' . $sociallink . ',id',
      'cssclass'    => 'required',
      'url'         => 'nullable|active_url'
    ];
}

Form Request documentation 中有一个这样的例子:

Also note the call to the route method in the example above. This method grants you access to the URI parameters defined on the route being called, such as the {comment} parameter in the example below:

Route::post('comment/{comment}');

关于Laravel 5.4 表单请求唯一验证: how to access id?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54677729/

相关文章:

java - 验证拦截器中的排除方法在 strut 2 中不起作用

function - 如何验证 Perl 中的函数参数?

laravel-5 - Laravel 5 PDF 创建、下载和打印

php - Laravel 中同一模型的多个关系

laravel - 如何在 Laravel 中通过自定义查询构建器使用预加载

php - 跨站点请求伪造验证失败。所需参数 "state"缺少 Laravel Sammyk/Facebook 包

php - Laravel eloquent join 三个join 使用find

mysql - Laravel创建表错误

database - 数据库约束是否应映射到业务逻辑

laravel-5 - 将代码推送到实时站点时,laravel 符号链接(symbolic link)会更改