andi79h
andi79h

Reputation: 1167

Loop variables in Laravel's Blade

I do quite a lot of loops in Laravel's Blade templates and sometimes, I have to remember some conditions like $found or $needToSave, something like that.

Here is a small example:

<?php $found = false; ?>
@foreach ($users as $user)
    @foreach ($user->posts as $post)

        @if ($post->something == "value")
            <?php $found = true; ?>
        @endif

        @if ($loop->parent->last)
            @if ($found)
                I really found something! Do something special!
            @endif
        @endif

    @endforeach
@endforeach

Now, is there a better way for the <?php $found = false|true ?> part? To me, this seems unclean and I am searching for a cleaner solution, which plays out with the template engine. I know about @php but this seems as ugly to me. Is there anything to assign local vars within the engine?

Cheers

Upvotes: 1

Views: 2418

Answers (1)

Alexey Mezenin
Alexey Mezenin

Reputation: 163758

If you don't need the variable later, you can refactor your code to:

@foreach ($users as $user)
    @foreach ($user->posts as $post)
        @if ($loop->parent->last && $post->something === 'value')
            I really found something! Do something special!
        @endif
    @endforeach
@endforeach

In case if you'll use it in the future, you can use @php and @endphp

In some situations, it's useful to embed PHP code into your views. You can use the Blade @php directive to execute a block of plain PHP within your template

https://laravel.com/docs/5.5/blade#php

Upvotes: 5

Related Questions