0
0
Laravelframework~15 mins

Raw PHP in Blade (@php) in Laravel - Mini Project: Build & Apply

Choose your learning style9 modes available
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
1
Create the Blade template skeleton
Create a Blade template file with an <h1> tag that will later show the greeting message. For now, leave the <h1> tag empty.
Laravel
Need a hint?

Start by writing the basic HTML structure with an <h1> tag inside your Blade template.

2
Add raw PHP block to get current hour
Inside the Blade template, add a raw PHP block using @php and @endphp. Inside this block, create a variable called $hour and set it to the current hour using date('H').
Laravel
Need a hint?

Use @php and @endphp to write raw PHP code inside Blade. Use date('H') to get the current hour as a string.

3
Add greeting logic inside the PHP block
Inside the same @php block, add a variable called $greeting. Use an if statement to set $greeting to 'Good morning' if $hour is less than 12, otherwise set it to 'Good afternoon'.
Laravel
Need a hint?

Use a simple if statement in PHP to check the hour and assign the greeting message.

4
Display the greeting message in the template
Below the @php block, display the $greeting variable inside the <h1> tag using Blade's echo syntax {{ }}.
Laravel
Need a hint?

Use {{ $greeting }} to show the greeting message inside the HTML.