Home > OS >  Laravel migration many to many relastionship
Laravel migration many to many relastionship

Time:11-17

I have many to many relationship between user and days. A day can have many users, a user can have many gifts. Is there any way to make this day_id unique with the users?

Example of table shown below:

**user_id  day_id**
    1       1
    1       1     cannot get prize in day 1 if he already got one
    2       1
    3       1
    1       2
    2       2
    2       2     {not again user_id 2 can get day_id 2 gift}

CodePudding user response:

Probably you could define a "role" column in users table to divide user and particular user, then use count() method to do the limitation in your controller.

CodePudding user response:

I actually solved this by simply adding a validation rule: 'day_id' => Rule::unique('user_day', 'day_id')->where(function ($query) { return $query->where('user_id', $this->user_id); }), 'user_id' => ['required', 'exists:users,id']

  • Related