问题
So I have a messages table with all messages. I want pinned messages to be at top and normal ones to follow after. I have been able to do this normally with the orderBy() method in my query.
However, I want to display some specific messages for all my pinned messages. I would like to have a header at the top of the pinned messages and a header at the top of the normal messages to let users know that pinned and normal messages are there.
Example:
My query:
$rows = Messages::where('active', true)->orderBy('pinned', 'desc')->get();
My view
@foreach ($rows as $row)
{{ $row->message }}
@endforeach
What I see
Message text 3
Message text 1
Message text 2
I have a few messages with "pinned" in the column in database. So I want the pinned ones to show at the top WITH DESCRIPTIONS. Something like this:
Pinned
----------
Message text 3
----------
Normal
----------
Message text 1
Message text 2
I have tried orderBy() and it's working pretty good, in terms of ordering it from pinned to normal, but I can't get it to show the "Pinned" and "Normal" message. How can I do this?
回答1:
Try something like this (change 1/0 to true/false or whatever you use):
In a controller:
$pinned = $rows->where('pinned', 1);
$normal = $rows->where('pinned', 0);
In a view:
@if(count($pinned) > 0)
Pinned
@foreach ($pinned as $row)
{{ $row->message }}
@endforeach
@endif
@if(count($normal) > 0)
Normal
@foreach ($normal as $row)
{{ $row->message }}
@endforeach
@endif
If real @foreach part is big, use partial and @each instead of @foreach to avoid code duplication.
Alternative
@foreach ($rows as $row)
@if ($row->pinned === 1 && !isset($pinnedShown))
Pinned
{{ $pinnedShown = true }}
@endif
@if ($row->pinned === 0 && !isset($normalShown))
Normal
{{ $normalShown = true }}
@endif
{{ $row->message }}
@endforeach
Short alternative
Not very readable, but if you just need short code, use something like this:
@foreach ($rows as $row)
<?php !($row->pinned == 1 && !isset($pin)) ? : $pin = call_user_func(function(){ echo 'Pinned'; return 1; });
!($row->pinned == 0 && !isset($nor)) ? : $nor = call_user_func(function(){ echo 'Normal'; return 1; }); ?>
{{ $row->message }}
@endforeach
来源:https://stackoverflow.com/questions/36783142/laravel-foreach-loop-show-a-specific-message-for-types-of-result