Performance: Raw PHP in Blade (@php)
Using raw PHP in Blade templates affects page rendering speed and can increase server processing time, impacting the time to first byte and overall load speed.
// In Controller $total = collect($items)->sum('price'); return view('cart', compact('total')); // In Blade <p>Total: {{ $total }}</p>
@php $total = 0; foreach($items as $item) { $total += $item->price; } @endphp <p>Total: {{ $total }}</p>
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Raw PHP in Blade (@php) with logic | Minimal DOM nodes added | No direct reflows | No direct paint cost | [X] Bad - slows server rendering |
| Pre-calculated data passed to Blade | Minimal DOM nodes added | No direct reflows | No direct paint cost | [OK] Good - faster server response |
@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