I'm using form request to validate data into update method. I'm trying to validate email as a unique value expect requested user email like this
public function rules() {
$user = $this->user();
return [
'name' => 'required|max:255|string',
'email' => 'required|email|max:255|unique:users,email,'.$user->id,
'restaurant' => 'required',
];
}
But it doesn't work, how to access requested user id into form request?
I will assume that you are posting a user object, where id
is included in your $request
data.
In case you are storing a new record and email needs to be available, you can use:
use Illuminate\Validation\Rule;
...
public function rules() {
return [
'name' => 'required|max:255|string',
'email' => ['required', 'email', 'max:255', Rule::unique('users')],
'restaurant' => 'required',
];
}
If you want to ignore your user->id, because you are updating your record and obviously the email is taken by the user:
use Illuminate\Validation\Rule;
...
public function rules() {
return [
'name' => 'required|max:255|string',
'email' => ['required', 'email', 'max:255', Rule::unique('users')->ignore($this->id)],
'restaurant' => 'required',
];
}