Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a XOR constraint via Laravel migration

Tags:

php

laravel

I am trying to build a table of this structure using Laravel's migrations feature:

------------------------------------
| Data  | Rules | Allow | Restrict |
------------------------------------
| item1 | rule1 | 1,3   |   null   |
| item2 | rule2 | null  |  2,5,6   |
------------------------------------

As in, for each entry either Allow or Restrict must possess a not null value, but not both. I've found this comment which sounds like the condition I need, but I need to express it in a format understandable to Laravel.

like image 582
Ivan T. Avatar asked Dec 31 '25 05:12

Ivan T.


1 Answers

I think there are 2 good solutions

  1. Seperate the data in 2 tables

Table1 -> data, rules, constraint (FK)

Table2-> id (PK, referenced by Table1), content (allow/restrict numbers), isAllow(bool)

That way you do the constraint in the database. This is the better solution, because now you don't have null values in your database. Normalisation is a good thing.

  1. Use the event listener to check before insert

https://laravel.com/docs/5.6/eloquent#events

public function creating(Table1 $t1)
{
       // check if 1 is null and 1 is not null before creating
}
like image 74
online Thomas Avatar answered Jan 02 '26 19:01

online Thomas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!