0
0
Laravelframework~30 mins

Control structures (@if, @foreach, @for) in Laravel - Mini Project: Build & Apply

Choose your learning style9 modes available
Building a Simple Product List with Laravel Blade Control Structures
📖 Scenario: You are creating a simple product list page for a small online store using Laravel Blade templates. You want to show the products with their prices, highlight expensive products, and display a message if no products are available.
🎯 Goal: Build a Blade template that uses @foreach to list products, @if to highlight expensive products, and @for to show a limited number of featured products.
📋 What You'll Learn
Create a $products array with exact product names and prices
Create a variable $expensiveThreshold to define the price limit for expensive products
Use @foreach to loop through $products and display each product's name and price
Use @if inside the loop to highlight products with price greater than $expensiveThreshold
Use @for to display the first 3 featured products from the $products array
💡 Why This Matters
🌍 Real World
Online stores and dashboards often need to display lists of items with conditional formatting and limited featured sections.
💼 Career
Understanding Blade control structures is essential for Laravel developers to build dynamic and maintainable web pages.
Progress0 / 4 steps
1
Create the products array
Create a PHP array called $products with these exact entries: ['Laptop' => 1200, 'Smartphone' => 800, 'Tablet' => 450, 'Headphones' => 150, 'Charger' => 50].
Laravel
Need a hint?

Use square brackets [] to create the array with keys as product names and values as prices.

2
Add the expensive price threshold
Create a variable called $expensiveThreshold and set it to 500.
Laravel
Need a hint?

Just assign the number 500 to the variable $expensiveThreshold.

3
Use @foreach and @if to list and highlight products
Write a Blade template snippet that uses @foreach ($products as $product => $price) to loop through the products. Inside the loop, use @if ($price > $expensiveThreshold) to add a <strong> tag around the product name for expensive products. Display each product name and price inside a <li> element.
Laravel
Need a hint?

Use @foreach to loop, @if to check price, and Blade curly braces {{ }} to show variables.

4
Use @for to display first 3 featured products
Add a Blade @for loop that runs from $i = 0 to less than 3. Inside the loop, display the product name and price from array_keys($products)[$i] and array_values($products)[$i] inside a <div> with class featured.
Laravel
Need a hint?

Use @for with $i from 0 to 2, and use array_keys($products)[$i] and array_values($products)[$i] to get product name and price.