Search code examples
laravelrequestlaravel-request

laravel custom request edit unique


i have custom request on laravel 5.5 this is the request

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',
        ];              
    }

now on method path i want to to ignore the current unique id and i wrote it like this

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

but its always telling me thats the username you are trying to update is already in use i dont want to do that from the controller i want to do it in the request thanks


Solution

  • you are using $this->id, here $this is not a User class but a Request instance, you may consider using $this->user()->id or auth()->id() or Auth::id() instead. if you have user id in route like users/{userId}, you can also use $this->route('userId').