Home > front end >  Laravel 7: Match two column dates with current date and show value depends on the condition
Laravel 7: Match two column dates with current date and show value depends on the condition

Time:06-15

Leave:

id user_id start_date end_date
1 2 2022-06-01 2022-06-03

Blade:

@foreach ($users as $row )
    <tr>
        <td>{{ $loop->iteration }}</td>
        <td>{{ $row->id }}</td>
        <td>{{ $row->name }}</td>
        <td>{{ $row->dpt->department }}</td>
        @php
           $today = Carbon\Carbon::now();
           $leave = App\Leave::where('user_id', $row->id)->whereBetween('') <!-- incomplete -->


         @endphp
         <td>Leave Status</td>
    </tr>
@endforeach

In this table, all user lists are shown. Here in the Leave Status column, it will show On Leave if the user is on leave today. I think I have to match today's date with start_date and end_date of the leave table and also match the user_id

What will be the eloquent query for this?

Example:

id name Leave Status
1 Jhon Present
2 Doe On Leave
3 Laura On Leave

CodePudding user response:

have you try this:

\Carbon\Carbon::now()->between($row->leaves()->last()->start_date,$row->leaves()->last()->end_date) ? 'On Leave' : 'Present';

CodePudding user response:

If you also have the relationships defined in the model you could load them with constraints in your controller:

$users = User::with(['leaves' => function ($query) {
    $query->where('start_date', '>=', Carbon::now()))
          ->where('end_date', '<=', Carbon::now()));
}])->get();

This way you don't have to query in your blade templates and you can just check if count($row->leaves) > 0

  • Related