Dieter
Dieter

Reputation: 1710

Laravel 4: making a combination of values/columns unique

I'm importing a bunch of csv entries in my database with Laravel 4.

I can't really point at one column that has to be unique, it's a combination of 5 columns that makes it unique. However: how does one define this in Laravel?

Option 1: schema builder
You can use the $table->unique('email') method, but that only seems to allow one column, not a combination of columns.

Option 2: Validation
Less preferable, but I could validate the model before inserting it. However, again, using 'unique:[table]' validation rules, it will return an error when just one of the column values isn't unique, not a combination of them.

Can anyone tell me how I should go about this?
I'm sure I'm missing something, but I could use a push in the right direction :-)

Thanks,

Dieter

Upvotes: 40

Views: 31156

Answers (5)

Allan Nila Chongwe
Allan Nila Chongwe

Reputation: 71

You can also do this;

$table->unique(["column1", "column2"], 'uq_columns');

Which means that you will have a unique column combination of all the columns i.e. column1 and column2

Upvotes: 7

JuanDMeGon
JuanDMeGon

Reputation: 1211

I know this question is for Laravel 4, but I just came across this on searches and found a solution for Laravel >= 5.3

Here it is:

Of course, the migration may look something like

$table->unique( array('email','name') );

Then to validate this, you do not need to use custom rules, just advanced rules:

'email' => Rule::unique('users')->where(function ($query) use ($request) {
    return $query->where('name', $request->name);
}),

Of course, you may want to validate name before of this. The name should be required so that you may finish with something like this:

'name' => 'required|max:255',
'email' => Rule::unique('users')->where(function ($query) use ($request) {
    return $query->where('name', $request->name);
}),

I hope it helps.

Upvotes: 2

srsajid
srsajid

Reputation: 1787

You can try this

$table->string("name");
$table->string("email")->unique("name")

Upvotes: -4

Felix
Felix

Reputation: 812

Use Schema Builder's unique() method to define your data model, as Antonio mentioned.

Additionally, if you want to use validation on your model, consider my custom Validator rule for multiple UNIQUE indexes: https://github.com/felixkiss/uniquewith-validator

Upvotes: 9

Antonio Carlos Ribeiro
Antonio Carlos Ribeiro

Reputation: 87789

You can combine:

$table->unique( array('email','name') );

And pretty much everything in Laravel will accept arrays to do whatever you need to with 'more than one'.

Upvotes: 94

Related Questions