In Laravel Blade templates, you can use @php
and @endphp
directives to embed PHP code blocks into the template.
Here’s an example:
@php
$name = 'Alice';
$age = 25;
@endphp
<p>Hello, my name is {{ $name }}. I am {{ $age }} years old.</p>
Inside the @php
block, you can use any PHP code you want, including control statements and functions.
@php
$name = 'Alice';
$age = 25;
if ($age > 21) {
$message = "You are old enough to drink!";
} else {
$message = "You are not old enough to drink.";
}
@endphp
<p>{{ $message }}</p>
You can also use the @foreach
directive inside a @php
block:
@php
$items = [1, 2, 3, 4, 5];
$total = 0;
@endphp
@foreach ($items as $item)
@php
$total += $item;
@endphp
@endforeach
<p>The total is {{ $total }}</p>
Note that you should use @php
blocks sparingly, as they can make your templates harder to read and maintain. If possible, you should try to use Blade directives and Laravel’s built-in functions to achieve the desired result.