Reputation: 13192
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?
Upvotes: 3
Views: 2115
Reputation: 13259
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 }}
Upvotes: 4