0

I'm a total Laravel Blade noob and trying to do something I know how to do in JavaScript but need to do in a Blade template.

I want to loop through this object below $site->links()->orderBy('position')->get() and evaluate each $link->type and push to one of two new arrays based on the value. So...

global $navlinks = [];
global $legallinks = [];

// main loop
@foreach($site->links()->orderBy('position')->get() as $link)

// blavascript concept of what I need. 
@if($link->type == 'nav') $navlinks.push($link)
@if($link->type == 'legal) $legallinks.push($link) 

...

// Do something with new $navlinks and $legallinks arrays

I hope this makes sense...

0

1 Answer 1

1

Well, that looks "logics" to me, so IMO it should be done somewhere else, but in blade you can do something like this:

@php
$navlinks = []; 
$legallinks = [];
@endphp

// main loop
@foreach($site->links()->orderBy('position')->get() as $link) 
  @if($link->type == 'nav') @php $navlinks[] = $link; @endphp
  @if($link->type == 'legal) @php $legallinks[] = $link; @endphp
@endforeach

or, since ->get() will return a Collection:

@php
  $res = $site->links()
     ->orderBy('position')
     ->get()
     ->reduce(function($acc, $val){
         $acc[$link->type][] = $val;
         return $acc;
       }, [
        'nav' => [],
        'legal' => []
     ])
@endphp
@foreach($res['legal'] as $legal) ... @endforeach
@foreach($res['nav'] as $nav) ... @endforeach
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.