Search code examples
phplaravellaravel-5.3laravel-blade

Why condition @if in laravel blade not working? (Laravel 5.3)


If my code is like this :

<ul class="test">
    @foreach($categories as $category)
        @if($loop->first)
            $category_id = $category->id
        @endif
    @endforeach
</ul>

There exist error :

Undefined variable: category_id (View: C:\xampp\htdocs\myshop\resources\views\front.blade.php)

If my code is like this :

<ul class="test">
    @foreach($categories as $category)
        @php
        if($loop->first)
            $category_id = $category->id
        @endphp
    @endforeach
</ul>

I works

Why the first way does not work?


Solution

  • Because you are trying to assign a variable in Blade view. Here are ways to assign variables in Blade template.

    {{--*/ $category_id = $category->id /*--}}
    <?php $category_id = $category->id ?>
    @php $category_id = $category->id @endphp
    

    The space between @if() and @endif is simply html. That's why you use curly braces to echo values {{ $value }}