Dev
Dev

Reputation: 1073

How to use collections function in blade template?

I try to control output flow in Blade template, for this I use collection function inside template:

@if(count($item->images))
   @if($item->images->count() > 1 && $item->images->count() < 3)
        {{$chunk = $item->images->forPage(0, 1)}} // It displays $chunk like as object (string) in template
   @endif
@endif

After this I try to display collection in $chunk:

@foreach($chunk as $image)
   // Show here
@endforeach

Upvotes: 0

Views: 1355

Answers (2)

Joel Hinz
Joel Hinz

Reputation: 25374

{{ some code php }}

Is the same as

<?php echo some php code; ?>

NOT the same as

<?php some php code; ?>

What you can do is either just relay the info to the loop:

@if(count($item->images))
   @if($item->images->count() > 1 && $item->images->count() < 3)
        @foreach($item->images->forPage(0, 1) as $image)
            // do stuff
        @endforeach
   @endif
@endif

Or you can use a package such as radic/blade-extensions (http://robin.radic.nl/blade-extensions/) and use @set() to set the variable.

Or you could just use regular PHP in the template, but that's not as nice of course.

Upvotes: 1

jaysingkar
jaysingkar

Reputation: 4435

Can't you do this,

@if(count($item->images))
   @if($item->images->count() > 1 && $item->images->count() < 3)
        @foreach($item->images->forPage(0, 1) as $image)
           // Show here
        @endforeach
   @endif
@endif

Upvotes: 1

Related Questions