Answer the question
In order to leave comments, you need to log in
How to validate a unique field when using the hasOne relation?
There is a standard table of users from Laravel Auth, there is a table with guids for these users:
I create a relation in User.php:
public function guid()
{
return $this->hasOne(Guid::class);
}
public function store()
{
$data = request()->validate([
'uid' => 'required',
]);
$guid = request()->user()->guid()->create($data);
}
Schema::create('guids', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('user_id')->unique();
$table->string('uid');
$table->timestamps();
});
Illuminate\Database\QueryException: SQLSTATE[23000]: Integrity constraint violation: 19 UNIQUE constraint failed: guids.user_id (SQL: insert into "guids" ("uid", "user_id", "updated_at", "created_at") values (52973-276-9929276-03525, 1, 2020-09-29 09:43:25, 2020-09-29 09:43:25))
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question