Home > database >  Check if a value exist in Laravel collection
Check if a value exist in Laravel collection

Time:12-24

I'm trying to make a time management schedule. The table is like this:

Days    | Start | End
Monday  | 08:00 | 11:00
Tuesday | 07:00 | 12:00
...

I want to keep showing days from Monday to Sunday even though in database there's no data for it.

I want the result to be like this:

Days    | Start | End   |
Monday  | 08:00 | 11:00 |
Tuesday | 07:00 | 12:00 |
...
Sunday  |   -   |   -   |  // if there's no sunday data in database it still 
                           // showing sunday but the start & end is empty

There's also a chance where the results of query is null, so it will end up error because I don't have any value inside variable when using foreach later in views.

This is my controller:

$work_hours = AttendanceGroupWorkHour::where('attendance_group_id', $id)->get();

And this is my view:

@foreach ($work_hours as $work_hour)
  <tr>
     <td> 
        {{ $work_hour->days)
     </td>
     <td>
        {{ $work_hour->start)
     </td>
     <td>
         {{ $work_hour->end)
      </td>
     </tr>
</tbody>
@endforeach

Sorry but I really don't have any idea how to do it. Any help would be helpful for me.

CodePudding user response:

Instead of iterating over $work_hours, which might be missing days that you want to display, iterate over the days of the week (or dates between your start/end, whatever you are doing). As a demonstration let's just iterate over this week.

In your Controller:

// First step is to make your $work_hours addressable.  Use keyBy()
// so that we can do something like $work_hours['Monday'].
$work_hours = AttendanceGroupWorkHour::where('attendance_group_id', $id)
    ->get()
    ->keyBy('days');

// Now let's build an array of every day this week - you would have
// to adjust this to match the dates in $work_hours.
$days = [];
$start = Carbon::now()->startOfWeek();
$end = Carbon::now()->endOfWeek();
for ($day = $start->copy(); $day->lte($end); $day->addDay()) {
    $days[] = $day->format('l'); // Eg "Monday"
}

// Now pass the full set of days to the view, along with your "data" days:
return view('some.view', [
    'days'       => $days,
    'work_hours' => $work_hours
]);

Now in your view:

@foreach ($days as $day)
    <tr>
        <td>{{ $day }}</td>
        <td>@if (isset($work_hours[$day]) {{ $work_hours[$day]->start }} @endif</td>
        <td>@if (isset($work_hours[$day]) {{ $work_hours[$day]->end }} @endif</td>
    </tr>
@endforeach
  • Related