Search code examples
laraveldesign-patternsrepositoryuniquerules

How to check the being unique of the model without sending the model to the update method in laravel?


Email and username are unique to the user.in validating the user update request،for email and user name I have this error:

"message": "Attempt to read property "id" on string",

this is method in UserRepository file:

public function update($request, $id)
{
    $new_request = (object)$request;
    $data = $new_request->all();
    $this->user::where('id', $id)->update($data);
    return http_response_code(201);
}

this is method in UserController:

public function update(UpdateUserRequest $request, $id)
{
    return $this->userRepository->update($request, $id);
}

this is UpdateUserRequest:

'username' => 'required|string',Rule::unique('users')->ignore($this->user->id),


Solution

  • If the id in the controller is the user ID that you need, you can access that id like this:

    'username' => 'required|string',Rule::unique('users')->ignore($this->route('id')),