Using Raw PHP in Blade Templates with @php
📖 Scenario: You are building a simple Laravel web page that shows a greeting message based on the current hour of the day. You want to use raw PHP inside your Blade template to decide which greeting to show.
🎯 Goal: Create a Blade template that uses the @php directive to write raw PHP code. The PHP code should get the current hour and set a greeting message variable. Then display the greeting message in the HTML.
📋 What You'll Learn
Create a variable
$hour inside @php that stores the current hour using date('H').Create a variable
$greeting inside @php that sets the greeting to 'Good morning' if $hour is less than 12, otherwise 'Good afternoon'.Display the
$greeting variable inside an <h1> tag in the Blade template.Use the
@php directive to write the raw PHP code block.💡 Why This Matters
🌍 Real World
Many Laravel projects use Blade templates to build web pages. Sometimes you need to run small PHP code snippets directly in the template for dynamic content.
💼 Career
Understanding how to mix PHP logic with Blade templates is important for Laravel developers to create flexible and dynamic views.
Progress0 / 4 steps