gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 15:18:39 25 4
gpt4 key购买 nike

我有以下表单请求:

<?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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com