Laravel 12 E-Commerce Project Tutorial
Making the Home Page Slider Dynamic
Hi everyone, welcome back to the Laravel E-Commerce Tutorial. This video focuses on making the Home Page Slider dynamic by creating a database table, a model, and fetching the slide data to display on the frontend.
-
Create Model and Migration for Slides
Run the following command in your command prompt to create the `Slide` model and its corresponding migration:
php artisan make:model Slide –m -
Define the `slides` Table Schema
Open the `create_slides_table` migration file (or `create_home_slider_table` as mentioned in the source) and add the following columns:
Schema::create("slides", function (Blueprint $table) {
$table->id();
$table->string("tagline");
$table->string("title");
$table->string("subtitle");
$table->string("link");
$table->string("image");
$table->boolean("status"); // 1 for active, 0 for inactive
$table->timestamps();
}); -
Run the Migration
Execute the migration to create the `slides` table in the database:
php artisan migrate -
Create the Admin `slider` Function
In `AdminController.php`, create a function to manage and display all existing slides in the admin panel. (Although this section details making the *frontend* dynamic, the source includes the admin function to populate the data.)
public function slider()
{
// Fetches all slides, ordered by creation date, paginated
$slides = HomeSlider::OrderBy("created_at","DESC")->paginate(10);
return view("admin.slider",compact("slides"));
} -
Fetch Dynamic Slides in `HomeController`
In your `HomeController`, update the `index` method to fetch active slides to be displayed on the home page.
public function index()
{
// Fetch up to 3 active slides (where status = 1)
$slides = Slide::where("status",1)->get()->take(3);
return view("index", compact("slides"));
} -
Update the Frontend View (`index.blade.php`)
Open `index.blade.php` and replace the static slider HTML with a `@foreach` loop that iterates over the `$slides` collection.
<div class="slider-active">
<div class="swiper-container">
<div class="swiper-wrapper">
@foreach ($slides as $slide)
<div class="single-slider swiper-slide animation-style-01">
<div class="slider-content">
<h2 class="title">
{{ $slide->title }}
</h2>
<p>
{{ $slide->subtitle }}
</p>
<a href="{{ $slide->link }}" class="btn btn-primary btn-hover-dark btn-margin">purchase now</a>
</div>
<div class="slider-images">
<img src="{{ asset("uploads/slides") }}/{{ $slide->image }}" width="707" height="477" alt="Slider" />
</div>
</div>
@endforeach
</div>
<div class="swiper-pagination"></div>
</div>
</div>
Verification and Testing ✨
After adding some initial slide data into the newly created `slides` table (using the admin panel, which should be implemented in subsequent steps, or directly via a seeder/database tool), refreshing the Home Page will display the slides dynamically fetched from the database.
