Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5.4 blade foreach loop

I am building a venue manangement system, and on the landing page, i m trying to show all the available slots to the visitors. The ones that have already been booked are shown as not available. I have created two variables, one that carries the info from the time table and the other from the booking table and tyring to use blade to compare and show. This is how I am trying to implement it in blade:

@foreach($times as $time)   
 @foreach($bookings as $booking)
    <tr>
        @if($time->availble_times == $booking->booking_time)
            <td>{{$time->availble_times}}: not available</td>
        @else
            <tr><td>{{$time->availble_times}}</td>
        @endif
            </tr>
 @endforeach    
@endforeach 

But what this does instead is show all the times for as many records in the bookings table. Like if there are two rows in the bookings table, it shows the times twice, and so on. Just in case, here is my controller function:

 public function times(){
    $times = Times::all();
    $bookings = Bookings::all();
    return view('/test2')->with('times', $times)->with('bookings', $bookings);
}

I recently started doing Laravel and cannot figure out this issue. My question is, how can i fix the n-times display issue and show the user which times are booked and which are available?

like image 504
Muhammad Muneeb ul haq Avatar asked Jun 11 '17 18:06

Muhammad Muneeb ul haq


1 Answers

I don't know how your data looks, but by looking at your code columns availble_times and booking_time are date fields. If Times model is dictionary for hours (like 1. 8.00, 2. 8:45, 3. 9:00) , and booking hour has to be in Times records, then you just need to invert the loops to display each time for each booking

@foreach($bookings as $booking)
    @foreach($times as $time)
        <tr>
            <td>{{ getImaginedChairNumber() }}</td>
            <td>{{ $time->availble_times }}</td>
            @if($time->availble_times == $booking->booking_time)
                {{-- There is already booking for that dictionary time --}}
                <td>not available</td>
            @else
                <td>available</td>
            @endif
        </tr>
    @endforeach
@endforeach

Should produce similar table:

╔═══════╦══════╦═══════════════╗
║ Chair ║ Time ║    Booking    ║
╠═══════╬══════╬═══════════════╣
║ A1    ║ 8:00 ║ not available ║
║ A1    ║ 8:45 ║ available     ║
║ A1    ║ 9:00 ║ not available ║
║ A2    ║ 8:00 ║ not available ║
║ A2    ║ 8:45 ║ not available ║
║ A2    ║ 9:00 ║ not available ║
║ A3    ║ 8:00 ║ available     ║
║ A3    ║ 8:45 ║ available     ║
║ A3    ║ 9:00 ║ not available ║
╚═══════╩══════╩═══════════════╝

Is this the correct form of the output table you expect? (I used this tool to draw ascii table https://senseful.github.io/web-tools/text-table/)

like image 121
Bartłomiej Sobieszek Avatar answered Nov 02 '22 22:11

Bartłomiej Sobieszek