如果我的代码是这样的:
<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 View 中分配一个变量。以下是在 Blade 模板中分配变量的方法。
{{--*/ $category_id = $category->id /*--}}
<?php $category_id = $category->id ?>
@php $category_id = $category->id @endphp
@if()
和@endif
之间的空格只是html。这就是为什么要使用大括号来回显值 {{ $value }}
关于php - 为什么在 laravel blade 中条件 @if 不工作? (拉拉维尔 5.3),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42359161/