E
E
Eugene2020-09-29 13:10:31
Laravel
Eugene, 2020-09-29 13:10:31

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);
    }


In the GuidController controller, in the store method, I create an entry through this relationship for the current user:

public function store()
    {
        $data = request()->validate([
            'uid' => 'required',
        ]);

        $guid = request()->user()->guid()->create($data);

    }


At the same time, in the migration of the Guid table, I set the uniqueness of the user_id field (I need to always have one guide per user):
Schema::create('guids', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('user_id')->unique();
            $table->string('uid');
            $table->timestamps();
        });


At the same time, if I call the store() method twice, I will get an error at the database level:
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))


The question is how to validate this user_id correctly, taking into account the fact that I do not pass it in the request, it takes "itself" from the hasOne relation and the corresponding user()->guid() function

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question