Introduction
Sometimes you need to write plain PHP code inside your Blade templates. The @php directive lets you do that easily.
Sometimes you need to write plain PHP code inside your Blade templates. The @php directive lets you do that easily.
@php
// Your PHP code here
@endphp@php to start writing PHP code and @endphp to end it.@php
$greeting = 'Hello, world!';
@endphp
<p>{{ $greeting }}</p>@php
$numbers = [1, 2, 3];
$sum = array_sum($numbers);
@endphp
<p>Sum: {{ $sum }}</p>@php
for ($i = 1; $i <= 3; $i++) {
echo "<p>Number: $i</p>";
}
@endphpThis Blade template uses raw PHP to decide a greeting based on the current hour. Then it shows a personalized message.
@php
$name = 'Alice';
$hour = date('H');
if ($hour < 12) {
$greeting = 'Good morning';
} elseif ($hour < 18) {
$greeting = 'Good afternoon';
} else {
$greeting = 'Good evening';
}
@endphp
<h1>{{ $greeting }}, {{ $name }}!</h1>Use @php only for small PHP snippets to keep your Blade templates clean.
For complex logic, consider moving code to controllers or view composers.
Remember to escape output with {{ }} to keep your app safe.
@php lets you write plain PHP inside Blade templates.
Use it for quick PHP code like variables, loops, or conditions.
Keep your templates simple by avoiding too much PHP logic inside them.
@php in a Laravel Blade template?@php@php directive lets you write plain PHP code inside Blade templates.@php is for raw PHP code [OK]@php?@php to start and @endphp to end raw PHP blocks.@php and @endphp to wrap PHP code.@php
$count = 3;
for ($i = 1; $i <= $count; $i++) {
echo "Item $i ";
}
@endphp@php $name = 'Alice' echo "Hello, $name!"; @endphp
@php to loop through $users = [['name' => 'Bob', 'age' => 25], ['name' => 'Sue', 'age' => 30]]; and echo each user's name and age?Pass the test and this pattern moves unknown