Laravel - Foreach loop - Show a specific message for types of result

£可爱£侵袭症+ 提交于 2019-12-24 05:52:46

问题


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

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