0
0
Laravelframework~5 mins

Raw PHP in Blade (@php) in Laravel

Choose your learning style9 modes available
Introduction

Sometimes you need to write plain PHP code inside your Blade templates. The @php directive lets you do that easily.

You want to run a small PHP calculation or logic inside a Blade view.
You need to define variables or arrays directly in the template.
You want to use PHP functions that Blade does not support directly.
You want to keep your template clean but still use PHP code snippets.
Syntax
Laravel
@php
    // Your PHP code here
@endphp
Use @php to start writing PHP code and @endphp to end it.
You can write multiple lines of PHP code inside this block.
Examples
This example sets a PHP variable inside the Blade template and then displays it.
Laravel
@php
    $greeting = 'Hello, world!';
@endphp
<p>{{ $greeting }}</p>
Here we use PHP to sum an array and show the result in the template.
Laravel
@php
    $numbers = [1, 2, 3];
    $sum = array_sum($numbers);
@endphp
<p>Sum: {{ $sum }}</p>
This example uses a PHP loop to print HTML paragraphs inside the Blade view.
Laravel
@php
    for ($i = 1; $i <= 3; $i++) {
        echo "<p>Number: $i</p>";
    }
@endphp
Sample Program

This Blade template uses raw PHP to decide a greeting based on the current hour. Then it shows a personalized message.

Laravel
@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>
OutputSuccess
Important Notes

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.

Summary

@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.