Laravel 12 E-Commerce Project Tutorial
Showing On Sale Products on the Home Page
Hi everyone, welcome back to the Laravel E-Commerce Project Tutorial. In this video, we will learn how to show products that are currently on sale dynamically on the home page.
-
Fetch On Sale Products in `HomeController`
Open your `HomeController.php` and update the `index` function (where you fetch other data for the home page). We need to query products that have a value set for the `sale_price` column. We will fetch up to 8 products in random order.
public function index()
{
// Fetch up to 8 products that have a non-null sale_price
$sproducts = Product::whereNotNull("sale_price")
->orWhere("sale_price","<>","")
->inRandomOrder()
->get()
->take(8);
// ... other data fetching logic ...
// Return the on-sale products to the view
return view("index", compact("slides", "sproducts"));
// Assuming "slides" from Part 45 is also passed
} -
Update the Frontend View (`index.blade.php`)
Open `resources/views/index.blade.php`. Find the section dedicated to "On Sale Products" and replace the static product list with a dynamic loop using the `$sproducts` collection.
<div class="product-tabs-content">
<div class="tab-content">
<div class="tab-pane fade show active" id="tab?">
<div class="swiper-container">
<div class="swiper-wrapper">
@foreach ($sproducts as $product)
<div class="swiper-slide">
<div class="single-product-02">
<div class="product-images">
<a href="{{ route("shop.product.details", ["product_slug" => $product->slug]) }}">
<img src="{{ asset("uploads/products") }}/{{ $product->image }}"
width="270" height="303" alt="{{ $product->name }}">
</a>
</div>
<div class="product-content">
<h4 class="title">
<a href="{{ route("shop.product.details", ["product_slug" => $product->slug]) }}">
{{ $product->name }}
</a>
</h4>
<div class="price">
<span class="sale-price">
@if ($product->sale_price)
<s class="sprice">${{ $product->regular_price }}</s>
${{ $product->sale_price }}
@else
${{ $product->regular_price }}
@endif
</span>
</div>
</div>
</div>
</div>
@endforeach
</div>
</div>
</div>
</div>
</div> -
Price Display Logic
The code uses conditional logic to display the pricing: if a `sale_price` exists, it shows the regular price with a strikethrough (`<s>`) next to the sale price; otherwise, it only displays the regular price.
Verification and Testing ✨
Save the files and refresh the Home Page. The "On Sale Products" section should now display the products that have a sale price configured in the database, with their discounted prices clearly shown.
