Josh Mountain
Josh Mountain

Reputation: 1950

Validating 'unique per user' rows in database in Laravel 4

I have a db table that looks like this:

Schema::create('types', function($table)
{
    $table->increments('id');
    $table->string('label', 128);
    $table->boolean('unique_items');
    $table->integer('user_id')->unsigned();
    $table->foreign('user_id')->references('id')->on('users');
    $table->timestamps();
});

My validation currently looks like this:

// Validate input for new Type
$validator = Validator::make(Input::all(),
    array(
        'label' => 'required|min:3|max:128|unique:types',
    )
);

What I would like to achieve is a user being able to create a Type where the label is unique to their user_id. So if user 1 makes a Type labeled books he could not create another one, however user 2 could create a books type as well.

As far as I can tell from the Laravel docs it is only possible to exclude a user from the unique search but not compare based on their id. Is there a way around this?

Upvotes: 0

Views: 776

Answers (1)

The Alpha
The Alpha

Reputation: 146201

You may add additional where clause to make a composite unique item, for example:

"label" => "required|min:3|max:128|unique:types,label,null,id,user_id,{$user_id}"

All you need to pass the $user_id here so this will make sure a type is unique to this user only. You may declare a method inside your model/Type like this:

public function setUniqueValidationRuleForType($user_id)
{
    static::$rules["label"] = "required|min:3|max:128|unique:types,label,null,id,user_id,{$user_id}";
    return $this; // This is optional
}

Now, before you create a new entry, just call this method to allow another entry for the user with the ID you passed in to the method. You may also check the documentation here.

Upvotes: 1

Related Questions