How to Use Raw PHP in Blade Templates in Laravel
To use raw PHP in a Blade template, wrap your PHP code inside the
@php and @endphp directives or use standard PHP tags like <?php ?>. This allows you to write plain PHP code directly within your Blade views safely and cleanly.Syntax
You can include raw PHP in Blade templates using two main ways:
- @php ... @endphp: Blade directive to write multiple lines of PHP code.
- <?php ... ?>: Standard PHP tags for inline PHP code.
The @php directive is preferred for readability and Blade compatibility.
php
@php
// Your PHP code here
$greeting = 'Hello from PHP!';
@endphp
<?php
// Another way to write PHP
$farewell = 'Goodbye from PHP!';
?>Example
This example shows how to define variables and echo them using raw PHP inside a Blade template.
php
@php
$name = 'Alice';
$age = 30;
@endphp
<p>Name: <?php echo $name; ?></p>
<p>Age: {{ $age }}</p>Output
<p>Name: Alice</p>
<p>Age: 30</p>
Common Pitfalls
Common mistakes when using raw PHP in Blade include:
- Using
<?php echo $var; ?>instead of Blade's{{ $var }}for simple output, which is less clean. - Not closing PHP tags properly causing syntax errors.
- Mixing too much raw PHP with Blade syntax, reducing readability.
Use raw PHP only when necessary, and prefer Blade syntax for output and control structures.
php
<p><?php echo $name; ?></p>
{{-- Right way: use Blade echo --}}
<p>{{ $name }}</p>Quick Reference
Summary tips for using raw PHP in Blade:
- Use
@php ... @endphpfor multiple lines of PHP. - Use
<?php ... ?>for inline PHP if needed. - Prefer Blade syntax like
{{ }}for output. - Keep raw PHP minimal to maintain clean templates.
Key Takeaways
Use @php ... @endphp directives to write raw PHP code cleanly in Blade templates.
Standard PHP tags also work but are less preferred in Blade views.
Prefer Blade syntax {{ }} for output to keep templates readable and safe.
Avoid mixing too much raw PHP with Blade to maintain clean and maintainable code.
Always close PHP tags properly to prevent syntax errors.