Home > Net >  Laravel many to many relastionship count
Laravel many to many relastionship count

Time:11-17

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??

CodePudding user response:

You need to use the count selector at the end of your eloquent request :

$userCount = users::all()->count();

CodePudding user response:

Perhaps you can try this:

$dayId = $request->day_id;

// Get the count of users from the chosen day id
$userCount = User::where('day_id', '=', $dayId)->count();

// Set the limit and make a validation
$dayLimit = 5
   if ($userCount > $dayLimit) {
    dd('Limit exceeded');
   }
   else {
    dd('Within limit');
   }

Edit: As suggested, you can create a UserLog model and migration to make easier queries later on. See sample code below:

$dayId = $request->day_id;

// Get today's date

   $timeStamp = Carbon::now()->format("h:i A");

// Check first if there's an existing log

  $findIfThereIsLog = UserLog::where('user_id', '=', Auth::User()->id)
  ->whereDate('created_at', Carbon::today()->startOfDay())
  ->first();

// Proceed with the logging if there's none

   if ($findIfThereIsLog === null) {

    $newUserLog = new UserLog;

    $newUserLog->user_id = Auth::User()->id;
    $newUserLog->day_id = $dayId;
    $newUserLog->save();

  }

  else {

    // Do nothing

  }

From there you can easily do queries like:

// Get the number of users from a particular day id

$dayId = $request->day_id;

$getUserFromDayId = UserLog::where('day_id', '=', $dayId)->count();

CodePudding user response:

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");
   }
  • Related