为什么条件 @if in laravel blade 不起作用? (Laravel 5.3)

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

如果我的代码是这样的:

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

存在错误:

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

如果我的代码是这样的:

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

我工作

为什么第一种方式不行?

因为您正试图在 Blade 视图中分配一个变量。以下是在 Blade 模板中分配变量的方法。

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

@if()@endif之间的space就是html。这就是为什么您使用花括号来回显值 {{ $value }}