Home > Net >  Making column value unique to one user only while others can have same value only once as well
Making column value unique to one user only while others can have same value only once as well

Time:08-11

I have an option to allow each user to create their own profile categories. I want user A and user B to be allowed to have cats category, but I don't want user A to be able to have another category he already has so the name and slug has to be unique to his profile only so that all users can have cats category but same user can't have a duplicated cats category.

My categories table

    public function up()
    {
        Schema::create('categories', function (Blueprint $table) {
            $table->id();

            $table->foreignId('user_id')
                ->constrained()
                ->onUpdate('cascade')
                ->onDelete('cascade');

            $table->string('name');
            $table->string('slug');
            $table->timestamps();
        });
    }

Is it only allowed in validation? And if so, how to write the validation for this rule? That this column has to be a unique value only to this user but other users can have same value in their profiles.

CodePudding user response:

If you want to make sure there are no duplicated category names for a user, you need to make sure that the pair user_id name is unique in categories table.

In order to do so, you need to define a composite unique key for those 2 columns:

$table->unique(["user_id", "name"]);

This way, the database won't allow any user_id to have multiple categories with the same name.

  • Related