You can do this in your migration file:
Schema::create('devplans', function ($table) {
// ...
$table->unique(array('level_id', 'building_id'));
});
As said here: http://laravel.com/api/4.2/Illuminate/Database/Schema/Blueprint.html#method_unique
Thanks kokokurak,
this is working, but all I'll get is this SQL error:
SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '1-2' for key 'devplans_building_id_level_id_unique' (SQL: insert into devplans
(time
, points
, building_id
, level_id
, created_by
, updated_by
, updated_at
, created_at
) values (6, 7, 1, 2, 1, 1, 2014-10-12 10:24:10, 2014-10-12 10:24:10))
How can I make a validation error out of this?
As it says, your data doesn't respect this uniqueness. You have pair duplicates. You should take care of your data first and then put this unique constrain.
Yes that is totally clear and working.
But how can I prevent that the error is shown like this and just show a normal validation error to the user?
You can add unique
validation rule with additional fields: http://laravel.com/docs/4.2/validation#rule-unique
Or you can use try .. catch block. Every erroneous SQL action will throw an exception.
I would love to add a unique validationrule, but I have no idea how to write one that fires when level_id and building_id in combination aren't unique. How can I do that?
Try either one of these:
'level_id' => 'unique:devplans,level_id,NULL,id,building_id,' . Input::get('building_id')
Or:
'building_id' => 'unique:devplans,building_id,NULL,id,level_id,' . Input::get('level_id')
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community