Laravel 9 Vue Js Datatables Tutorial with Example

Laravel Vue js Datatables Example; In this step by step tutorial, we will explain how to use vuejs datatable package for showing lists of database records in laravel vue js app.

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. So, let’s see how to build datatable in laravel application using the vue js components.

Laravel Vue JS Datatables Example

Here we will show you how to implement datatable in the laravel vue app and how to immaculately use the vuejs-datatable library within the laravel vue js framework.

Follow the following steps to integrate and use vue js dataTables in laravel 9 app:

  • Step 1: Download Laravel App
  • Step 2: Connect App to Database
  • Step 3: Create Model And Migration
  • Step 4: Make Routes
  • Step 5: Create Controller
  • Step 6: NPM Configuration
  • Step 7: Create Vue Component
  • Step 8: Initialize Vue with Laravel
  • Step 9: Run Development Server

Install Laravel 9 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

Go into the app:

cd laravel-vue-datatables

Connect App to Database

After successfully install laravel new application, Go to project root directory and open .env file and set up database credential as follow:

DB_CONNECTION=mysql 
DB_HOST=127.0.0.1 
DB_PORT=3306 
DB_DATABASE=database name here
DB_USERNAME=database username here
DB_PASSWORD=database password here

Create Model And Migration

Next step, we need to execute the following command on terminal:

php artisan make:model Post -fm

This command will create one model name post.php, PostFactory.php and one migration file for the posts table.

Now open create_posts_table.php migration file from database>migrations and update following code:

<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreatePostsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
       Schema::create('posts', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('title');
            $table->string('slug');
            $table->timestamps();
      });
    }
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('posts');
    }
}

Next, migrate the table using the below command:

php artisan migrate

Next, Navigate to app/Models/Post.php and update the following code into Post.php model as follow:

<?php
 
namespace App\Models;
 
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
 
class Post extends Model
{
    use HasFactory;
 
    protected $guarded = [];
}

Next, Navigate to database/factories and open PostFactory.php. Then update the following code into it as follow:

/** @var \Illuminate\Database\Eloquent\Factory $factory */
use App\Models\Post;
use Faker\Generator as Faker;
$factory->define(Post::class, function (Faker $faker) {
    return [
       'title' => $faker->sentence,
       'slug' => \Str::slug($faker->sentence)
    ];
});

and then execute the following commad on terminal to generate fake data using faker as follow:

php artisan tinker
//and then
factory(\App\Models\Post::class,100)->create()
exit

Make Routes

Next step, go to routes folder and open web.php file and add the following routes into file:

routes/web.php

use App\Http\Controllers\PostController;
 
Route::get('posts', [PostController::class, 'index']);

Create Controller

Next step, open command prompt and execute the following command to create a controller by an artisan:

php artisan make:controller PostController

After that, go to app\Http\Controllers and open PostController.php file. Then update the following code into PostController.php file:

<?php 
namespace App\Http\Controllers;
use App\Models\Post;
use Illuminate\Http\Request;
class PostController extends Controller
{
    public function index(Request $request)
    {
        $posts = Post::get();
        return response()->json($posts);
         
    }
}

NPM Configuration

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

Create Component

Next step, go to resources/assets/js/components folder and create a file called DataTableComponent.vue.

Now, update the following code into DataTableComponent.vue components file:

<template>
    <div class="container">
        <div class="row justify-content-center">
            <div class="col-md-8">
                <div class="card">
                    <div class="card-header">Laravel Vue Datatables Component Example </div>
   
                    <div class="card-body">
                        <datatable :columns="columns" :data="rows"></datatable>
                        <datatable-pager v-model="page" type="abbreviated" :per-page="per_page"></datatable-pager>
   
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>
   
<script>
   
    import DatatableFactory from 'vuejs-datatable';
   
    export default {
        components: { DatatableFactory },
        mounted() {
            console.log('Component mounted.')
        },
        data(){
            return {
                columns: [
                        {label: 'id', field: 'id'}, 
                        {label: 'Title', field: 'title'},
                        {label: 'Slug', field: 'slug'}
                    ],
                rows: [],
                page: 1,
                per_page: 10,
            }
        },
        methods:{
            getPosts: function() {
                axios.get('/posts').then(function(response){
                    this.rows = response.data;
                }.bind(this));
            }
        },
        created: function(){
            this.getPosts()
        }
    }
</script>

Now open resources/assets/js/app.js and include the DataTableComponent.vue component as follow:

require('./bootstrap');
window.Vue = require('vue');
Vue.component('datatable-component', require('./components/DataTableComponent.vue').default);
const app = new Vue({
    el: '#app',
});

Initialize Vue with Laravel

In this step, navigate to resources/views and create one folder named layouts. Inside this folder create one blade view file named app.blade.php file.

Next, Navigate to resources/views/layouts and open app.blade.php file. Then update the following code into app.blade.php file as follow:

<!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>Laravel 9 Vue JS DataTable Example Tutorial - Tutsmake.com</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>

Next, Navigate to resources/views/ and open welocome.blade.php. Then update the following code into welcome.blade.php file as follow:

@extends('layouts.app')
@section('content')
<div class="container">
    <div class="row justify-content-center">
         
        <div class="col-md-8">
            <div class="card">
                <div class="card-header">Laravel Vue Js DataTable Example</div>
                     
                <div class="card-body">
                  <datatable-component></datatable-component>
                </div>
                 
            </div>
        </div>
    </div>
</div>
@endsection 

Strart Your Application

To start the development server by executing the following command on command prompt or terminal:

npm run dev
or 
npm run watch

In this laravel vue js datatable example, we have learned how to use vue js dataTable package in laravel vue js apps.

Leave a Comment