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 dayoff
s of each user)
2
Answers
you can use ‘whereHas’
To retrieve all users with their holidays for a specific month and year: