Skip to content
Advertisement

Laravel many to many relastionship count

I have two tables. User and days, with many to many relationship. user_days : user_id, day_id

public function users()
{
    return $this->belongsToMany(User::class, 'user_day');
}

public function days()
{
    return $this->belongsToMany(Day::class, 'user_day');
}

I want to get the count number of users in day_id = 1 {for a particular day} or something like this. Any way to get count from pivot table? This function didnot work.

public function assign_prize(Request $request)
{
    $userCount = $this->user->days()->withCount('users')->where($request->day_id, 'day_id')->get();
    $giftLimit = Day::where('id', $request->day_id)->get();
    if ($userCount > $giftLimit) {
        return problem(__("Gift for the current day has been finished!!"), 500, "Gift Assign Failed");
    }

the table structure ?

Schema::create('user_day', function (Blueprint $table) {
    $table->increments('id');
    $table->integer('user_id')->unsigned();
    $table->integer('day_id')->unsigned();
    $table->boolean('assigned')->default(0);
    $table->timestamps();
});

How do I find the user count of users on that particular day??

Advertisement

Answer

Get the count of users related to that day.

public function assign_prize(Request $request)
{
   
   $day = Day::withCount('users')->find($request->day_id);

   if ($day->users_count > $day->gift_limit) {
       return problem(__("Gift for the current day has been finished!!"), 500, "Gift Assign Failed");
   }
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement