Create Laravel 8 Dynamic Image Slider with Vue Component using Owl Carousel Plugin

Last updated on by Digamber

This comprehensive tutorial will help you understand how to integrate responsive image carousel slider dynamically with Vue js components in Laravel 8 application using Owl carousel plugin from the absolute beginning.

Owl carousel is a popular open-source JavaScript based carousel slider; it offers numerous features for enhancing your content’s interactivity. Some of its core features are responsiveness, touch, drag ‘n’ drop support, supports modern browsers not only but also supports zombie browsers.

This Laravel 8 Vue js owl carousel slider example covers all the profound steps, respectively to dynamically fetch images from the database and display in slider using owl carousel slider in Laravel.

Carousel is usually used on a web page to notify about the other important idea or topic. Ideally, they are used on home pages to grab the user’s attention. You can show products, posts, news any other essential information with it.

If you want to show images/content in laravel vue js with an owl carousel slider, then you are in the right place. We will share with you how to display multiple images in the Laravel vue js application.

Create Laravel Application

The first step begins with creating a new laravel application; go to your console and run the below command:

composer create-project laravel/laravel laravel-vue-carousel-slider-example --prefer-dist

Adding Database Details

Once the app is installed, head over to project root, open the .env file, and put your database details to invoke the database connection with laravel.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=db
DB_USERNAME=root
DB_PASSWORD=

Setting Up Model & Migration

Create a new Post model with artisan command:

php artisan make:model Post -m

Place the below code in app/Models/Post.php file:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    use HasFactory;
    protected $fillable = [
        'title',
        'picture'
    ];
}

Add code in database/migrations/create_posts_table.php:

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreatePostsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->string('picture');            
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('posts');
    }
}

After defining Post table values, run migration to add them into the database:

php artisan migrate

Install Vue Dependencies

In this step, you have to install Vue dependencies so run the command:

composer require laravel/ui
php artisan ui vue

Install vue owl carousel package in Laravel app:

npm install -s vue-owl-carousel

Run command to compile your fresh scaffolding:

npm install && npm run dev

Adding Dummy/Fake Images Data

This step explains to you how to create a custom factory class which is essential to generate the fake images data inside the database.

php artisan make:factory PostFactory --model=Post

Put the below code in database\factories\PostFactory.php:

<?php

namespace Database\Factories;

use App\Models\Post;
use Illuminate\Database\Eloquent\Factories\Factory;

class PostFactory extends Factory
{
    /**
     * The name of the factory's corresponding model.
     *
     * @var string
     */
    protected $model = Post::class;

    /**
     * Define the model's default state.
     *
     * @return array
     */
    public function definition()
    {
        return [
            'title' => $this->faker->name,
            'picture' => $this->faker->imageUrl(200, 180, 'cats', true, 'Faker')
        ];
    }
}

Run command to enter into tinker Psy shell:

php artisan tinker

Next, define the Post model name with the factory() method and generate test data:

Post::factory()->count(20)->create()

Read detailed article: How to create dummy data in Laravel with factory tinker

Generate & Set Up Controller

Now you have to run the command to generate a controller:

php artisan make:controller CarouselController

Add code in app\Http\Controllers\CarouselController.php file:

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Post;

class CarouselController extends Controller
{
    public function index()
    {
        return view('welcome');
    }

    public function carousel(Request $request)
    {
        $data = Post::get();
        return response()->json($data);
    }
}

Create Routes

Create two routes to bring blade view of the carousel slider into the view. Similarly, create another route for getting the image and other data from the server.

Head over to routes/web.php file, import controller on top also defines a route with get method:

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\CarouselController;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
 
Route::get('/', [CarouselController::class, 'index']);

Route::get('/image-slides', [CarouselController::class, 'carousel']);

Create Owl Carousel Vue Component in Laravel

Go to resources/js/components/ExampleComponent.vue file put the below code within:

<template>
    <div class="container">
        <div class="row justify-content-center">
            <div class="col-md-8">
                <div class="card">
                    <div class="card-body">
                        <carousel v-if="imgData.length > 0">
                            <div v-for="(img, index) in imgData" :key="index">
                                <img :src="img.picture" :alt="img.title" >
                            </div>
                        </carousel>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
    
    import carousel from 'vue-owl-carousel'

    export default {
        components: {
            carousel
        },
        props: {
            msg: String
        },
        data() {
            return {
                imgData: []
            }
        },          
        mounted() {
            axios
            .get('http://127.0.0.1:8000/image-slides')
            .then(res => {
                this.imgData = res.data;
            });
        }      
    }

</script>

You can check out the vue slider component configurations on the resources/js/app.js file:

/**
 * First we will load all of this project's JavaScript dependencies which
 * includes Vue and other libraries. It is a great starting point when
 * building robust, powerful web applications using Vue and Laravel.
 */

require('./bootstrap');

window.Vue = require('vue');

/**
 * The following block of code may be used to automatically register your
 * Vue components. It will recursively scan this directory for the Vue
 * components and automatically register them with their "basename".
 *
 * Eg. ./components/ExampleComponent.vue -> <example-component></example-component>
 */

// const files = require.context('./', true, /\.vue$/i)
// files.keys().map(key => Vue.component(key.split('/').pop().split('.')[0], files(key).default))

Vue.component('example-component', require('./components/ExampleComponent.vue').default);

/**
 * Next, we will create a fresh Vue application instance and attach it to
 * the page. Then, you may begin adding components to this application
 * or customize the JavaScript scaffolding to fit your unique needs.
 */

const app = new Vue({
    el: '#app',
});

Create Laravel Blade View

Next, you need to create an app.blade.php view file inside the resources/views/layout folder, also paste the below code within:

<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="csrf-token" content="{{ csrf_token() }}">
    
    <title>Owl Carousel Slider in Laravel 8 Vue JS App Example</title>

    <script src="{{ asset('js/app.js') }}" defer></script>
    <link href="{{ asset('css/app.css') }}" rel="stylesheet">
    @stack('fontawesome')
</head>
<body>
    <div id="app">
        <main class="py-4">
            @yield('content')
        </main>
    </div>
</body>
</html>

Finally, head over to resources/views/welcome.blade.php file and paste the following code to call the vue carousel slider component in laravel blade view:

@extends('layout.app')
@section('content')
<div class="container">
    <div class="row justify-content-center">
         
        <div class="col-md-8">
            <div class="card">
                <div class="card-header text-center">How to Use Owl Carousel in Laravel 8 Vue Examle</div>
                     
                <div class="card-body">
                  <example-component></example-component>
                </div>
                 
            </div>
        </div>
    </div>
</div>
@endsection

Thereafter, you have to open the console and run the node development server:

npm run watch

Open another console as well and start the laravel development server:

php artisan serve

Here is the owl carousel slider integration example in Laravel and Vue js application:

http://127.0.0.1:8000

Laravel 8 Dynamic Vue JS Owl Carousel Slider Example

Summary

Eventually, Laravel 8 and Vue.js owl carousel slider tutorial is over. In this tutorial, you have seen how to create a dynamic carousel slider with the Vue js component in the Laravel application using the Owl carousel plugin. I hope you will love it and share it with others.

Download tutorial code from GitHub.