Create Datatables in Laravel 8 Vue JS Application

Last updated on: by Editorial Team

This is a complete Laravel 8 Vue js datatable example; In this step by step tutorial, we will explain how to implement Datatables in Laravel Vue JS application using the third-party vuejs-datatable library.

The vuejs-datatable package provides the simple way to show a list of data in tabular form, not just that it also helps you create dynamic datatable with filtering, sorting and pagination functionalities.

Datatable is used to display complex data exquisitely; a user can quickly sort, filter and paginate data for its use. Immaculate information is a need for the current time. The whole world runs on it, and we are here to explain how to build datatable in laravel application using the vue js components.

Throughout this laravel vue js datatable example you will create a blogs table, add some fake records and display those blogs in a datatable fetching from database using the GET request with the help of Vue Axios API in a laravel application.

Laravel 8 Vue JS Datatables Example

By the end of this tutorial, you will have a proper idea of how to implement datatable in the laravel vue app and how to immaculately use the vuejs-datatable library within the laravel vue js framework.

Here is the list of tasks that we are going to cover in this tutorial:

  • Create a laravel project
  • Make database connection
  • Generate and configure model, Run migration
  • Create routes
  • Generate and setting up the controller
  • Setting up vue UI in laravel
  • Configure a vue component
  • Setting up views and vue components
  • Run application

Install Laravel App

On the console, screen type the following command and hit enter to generate a new laravel project. You can ignore this step if the app is already installed:

composer create-project laravel/laravel laravel-vue-datatables --prefer-dist

Database Connection

In the second step you have to add the database details inside the .env config file as given below:

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

Model and Migration

You have to create the blog table, add the table values in the database. But first, use the command to crate Model and migration files:

php artisan make:model Blog -m

Insert the given below code in database/migrations/create_blogs_table.php:

<?php

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

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

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

Add code in app/Models/Blog.php file:

<?php

namespace App\Models;

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

class Blog extends Model
{
    use HasFactory;
    protected $fillable = [
        'title', 
        'url', 
        'category',
        'description'
    ];    
}

In subsequent step run migration to add products table into the database:

php artisan migrate

Add Test Data with Factory

You have to generate a blog factory class that helps to generate test data for the laravel vue datatables:

php artisan make:factory BlogFactory --model=Blog

Next, add the code in database\factories\BlogFactory.php:

<?php

namespace Database\Factories;

use App\Models\Blog;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;

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

    /**
     * Define the model's default state.
     *
     * @return array
     */
    public function definition()
    {
        return [
            'title' => $this->faker->name,
            'url' => Str::slug($this->faker->name),
            'category' => $this->faker->name,
            'description' => $this->faker->text,
        ];
    }
}

Run tinker command to get inside the Psy Shell:

php artisan tinker
Blog::factory()->count(500)->create()

Define Controller

Now, you have to create the controller which will contain the logic to get the blogs data from the database:

php artisan make:controller BlogController

Update the app\Http\Controllers\BlogController.php file:

<?php

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

class BlogController extends Controller
{
    public function index(Request $request)
    {
        return view('welcome');
    }

    public function getBlogs(Request $request)
    {
        $blogs = Blog::get();
        return response()->json($blogs);
    }    
}

Construct Route

You need to open the routes/web.php, also update the file with the following code:

<?php

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

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
*/


Route::get('/', [BlogController::class, 'index']);

Route::get('/blogs', [BlogController::class, 'getBlogs']);

Install Laravel Vue UI

Next, you have to install laravel Vue UI:

composer require laravel/ui
php artisan ui vue

To install vue js datatable package, use the following command:

npm install vuejs-datatable

Then, run command to install npm dependencies:

npm install

Setting Up Vue JS in Laravel

Create BlogTable.vue in resources/js/components/ folder, place the following code in resources/js/components/DatatableComponent.vue file:

<template>
    <div>
        <bootstrap-4-datatable :columns="columns" :data="rows" :filter="filter" :per-page="perPage"></bootstrap-4-datatable>
        <bootstrap-4-datatable-pager v-model="page" type="abbreviated"></bootstrap-4-datatable-pager>
    </div>
</template>

<script>
    export default {
        data() {
            return {
                columns: [{
                        label: 'id',
                        field: 'id'
                    },
                    {
                        label: 'title',
                        field: 'title'
                    },
                    {
                        label: 'category',
                        field: 'category'
                    },
                    {
                        label: 'description',
                        field: 'description'
                    }
                ],
                rows: [],
                page: 1,
                filter:  '',
                perPage: 12,
            }
        },
        methods: {
            showBlogs: function () {
                axios.get('/blogs').then(function (res) {
                    this.rows = res.data;
                }.bind(this));
            }
        },
        created: function () {
            this.showBlogs()
        }
    }

</script>

Now, you need to register the Vue JS component, paste the following code in resources/js/app.js:

require('./bootstrap');

window.Vue = require('vue');

import 'vuejs-datatable/dist/themes/bootstrap-4.esm';
import { VuejsDatatableFactory } from 'vuejs-datatable';
Vue.use( VuejsDatatableFactory );


Vue.component('datatable-component', require('./components/DatatableComponent.vue').default);

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

Next, invoke the vue component by adding into the resources/views/welcome.blade.php file:

@extends('layout.app')
@section('content')

<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-8">
            <datatable-component></datatable-component>
        </div>
    </div>
</div>
@endsection

Let’s set up Vue layout, create layout directory within resources/views path also create app.blade.php file.

Add following code in resources/views/layout/app.blade.php:

<!doctype html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="csrf-token" value="{{ csrf_token() }}" />

    <title>Laravel Vue JS Datatables Demo</title>

    <script src="{{ asset('js/app.js') }}" defer></script>
    <link href="{{ asset('css/app.css') }}" rel="stylesheet">
</head>

<body>
    <div id="app">
        <main class="py-4">
            @yield('content')
        </main>
    </div>
</body>

</html>

Start Laravel Vue CRUD App

To start the CRUD app, you need to run the two following commands respectively in two different terminals simultaneously:

Open the terminal and execute the below command to compiles the assets. After using this command you won’t have to worry about re-starting the server every time you make a change in the vue component files.

npm run watch
php artisan serve

Check the app on the browser:

http://127.0.0.1:8000

Summary

Thats all for now, you have just completed the tutorial, which will help you create and implement datatables in Laravel Vue js app. I hope this tutorial will help you understand every concept of datatables in laravel vue.