Laravel 5.4 blade foreach loop

给你一囗甜甜゛ 提交于 2019-12-01 05:53:20

问题


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?


回答1:


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/)



来源:https://stackoverflow.com/questions/44487492/laravel-5-4-blade-foreach-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!