skip to Main Content

I have User and Holiday models related this way:

User model:

class User extends Authenticatable
{

    public function holidays(): HasMany
    {
         return $this->hasMany(Holiday::class);
    }

Holiday model:

class Holiday
{
    protected $fillable = [
        'dayoff', // DATE YYYY-MM-DD
        'user_id',
    ];

    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class);
    }

Given $month and $year, I would like to get all the users and their related holidays (dayoff).

How can I achieve that ?

Edit:

I re-wrote the below answer this way:

use IlluminateDatabaseEloquentBuilder;

$users = User::whereHas('holidays', function (Builder $query) use ($year, $month) {
    $query->whereYear('dayoff', $year)->whereMonth('dayoff', $month);
})->get();

But this gives the list of users without their related holidays (list of dayoffs of each user)

2

Answers


  1. you can use ‘whereHas’

    $dayoff = Carbon::today();
    User::whereHas('holidays', function ($q) use ($dayoff) {
                $q->where('dayoff', $dayoff);
            })->get();
    
    Login or Signup to reply.
  2. To retrieve all users with their holidays for a specific month and year:

     // Assuming $month and $year are passed as query parameters
        $month = $request->query('month');
        $year = $request->query('year');
    
        // Retrieve all users with their holidays for the specified month and year
        $users = User::with(['holidays' => function ($query) use ($month, $year) {
            $query->whereMonth('dayoff', '=', $month)
                  ->whereYear('dayoff', '=', $year);
        }])->get();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search