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


so have messages table messages. want pinned messages @ top , normal ones follow after. have been able orderby() method in query.

however, want display specific messages pinned messages. have header @ top of pinned messages , header @ top of normal messages let users know pinned , normal messages there.

example:

my query:

$rows = messages::where('active', true)->orderby('pinned', 'desc')->get(); 

my view

@foreach ($rows $row)     {{ $row->message }} @endforeach 

what see

message text 3 message text 1 message text 2 

i have few messages "pinned" in column in database. want pinned ones show @ top descriptions. this:

pinned ---------- message text 3 ---------- normal ---------- message text 1 message text 2 

i have tried orderby() , it's working pretty good, in terms of ordering pinned normal, can't show "pinned" , "normal" message. how can this?

try (change 1/0 true/false or whatever use):

in controller:

$pinned = $rows->where('pinned', 1); $normal = $rows->where('pinned', 0); 

in view:

@if(count($pinned) > 0)     pinned      @foreach ($pinned $row)         {{ $row->message }}     @endforeach @endif  @if(count($normal) > 0)     normal      @foreach ($normal $row)         {{ $row->message }}     @endforeach @endif 

if real @foreach part big, use partial , @each instead of @foreach avoid code duplication.

alternative

@foreach ($rows $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 readable, if need short code, use this:

@foreach ($rows $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 

Comments

Popular posts from this blog

html - Styling progress bar with inline style -

java - Oracle Sql developer error: could not install some modules -

How to use autoclose brackets in Jupyter notebook? -