laravel自定义请求编辑唯一

时间:2017-09-27 10:51:43

标签: laravel request laravel-request

我在laravel 5.5上有自定义请求 这是请求

public function rules()
{
    if($this->method() == 'POST')
    {
        return [
            'user_name' => 'required|unique:users|max:40|min:1',
            'user_email' => 'required|email|unique:users|max:40|min:3',
            'user_phone' => 'required|max:40|min:1',
            'password' => 'required|min:3',
            'image' => 'image|mimes:jpg,jpeg,gif,png|max:2048',
        ];          
    }
    elseif($this->method() == 'PATCH')
    {
        return [
            'user_name' => 'required|min:1|max:40|unique:users,user_name,'.$this->id,
            'user_email' => 'required|email|unique:users|max:40|min:3',
            'user_phone' => 'required|max:40|min:1',
            'password' => 'required|min:3',
            'image' => 'image|mimes:jpg,jpeg,gif,png|max:2048',
        ];              
    }

现在在方法路径上 我想忽略当前的唯一ID 我就这样写了

'user_name' => 'required|min:1|max:40|unique:users,user_name,'.$this->id,

但它始终告诉我,您尝试更新的用户名已经在使用中 我不想从控制器那样做 我想在请求中这样做 谢谢

1 个答案:

答案 0 :(得分:3)

您使用的是$this->id,此处$this不是User类,而是Request实例,您可以考虑使用$this->user()->idauth()->id()Auth::id()代替。如果您在users/{userId}等路线中拥有用户ID,则还可以使用$this->route('userId')