Vue js Live Search Functionality in Laravel 10

Vue js Live Search Functionality in Laravel 10

Adding live search functionality to a Laravel Vue.js app is a straightforward process. Live search allows users to search for specific data without needing to refresh the page. This can be achieved by utilizing Axios and AJAX to make HTTP requests to the server and retrieve data from the database.

So, In this tutorial, you will learn how to create a live search in laravel 10 vue js applications.

How to Create Live Search in Laravel 10 Vue JS App

  • Step 1: Setup Laravel 10 App
  • Step 2: Configure Database to Laravel App
  • Step 3: Run Make auth Command
  • Step 4: Create Model And Migration
  • Step 5: Install and Configure Vue.js
  • Step 6: Define Routes
  • Step 7: Create Controller By Command
  • Step 8: Make an HTTP request using Axios and Display Data
  • Step 9: Create Blade Views And Initialize Vue Components
  • Step 10: Run the Development Server

Step 1: Setup Laravel 10 App

First of all, Open your terminal or command prompt.

Then execute the following command into it to download or install Laravel 10 new setup in your server:

 composer create-project --prefer-dist laravel/laravel blog 

Step 2: Configure Database to Laravel App

Once you have installed laravel 10 apps on your server. Now, you need to configure the database with this app.

So. Go to your project root directory and open .env file. Then set up the database credential in .env file as follow:

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

Step 3: Run Make auth Command

Next step, Execute the following commands on terminal to install laravel/ui and implement auth system:

cd blog
composer require laravel/ui --dev
php artisan ui vue --auth

This laravel laravel/ui package provides a quick way to scaffold all of the routes, controller and views with authentication.

Step 4: Create a Model And Migration

In this step, you need to execute the following command on the terminal to create the post model and migration file:

php artisan make:model Post -fm

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

Now open the create_posts_table.php migration file from database>migrations and replace up() function with the 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->unsignedBigInteger('user_id');
            $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 your 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:

<?php

use Faker\Generator as Faker;

use App\Models\Post;

$factory->define(Post::class, function (Faker $faker) {
    return [
       'title' => $faker->sentence,
       'slug' => \Str::slug($faker->sentence),
       'user_id' => 1
    ];
});

and then execute the following command to generate fake data using faker as follow:

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

Step 5: Install and Configure Vue.js

In this step, You need to setup Vue and install Vue dependencies using NPM. So execute the following command on command prompt:

php artisan preset vue

Install all Vue dependencies:

npm install

Step 6: Define Routes

In this step, Visit routes directory and open web.php file and add the following routes into your file:

routes/web.php

use App\Http\Controllers\PostController;

Route::get('search', [PostController::class, 'index']);

Route::get('res-search', [PostController::class, 'search']);

Step 7: Create Controller By Command

Next step, open your 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 your PostController.php file:

<?php
namespace App\Http\Controllers;
use App\Models\Post;
use Illuminate\Http\Request;
use Facades\App\Repository\Posts;
class PostController extends Controller
{
    public function index()
    {   
        return view('search');
    }
    public function search(Request $request)
    {
        $posts=Post::where('title',$request->keywords)->get();
        return response()->json($posts);
        
    }
}

Step 8: Make an HTTP request using Axios and Display Data

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

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

<template>
    <div>
        <input type="text" v-model="keywords">
        <ul v-if="results.length > 0">
            <li v-for="result in results" :key="result.id" v-text="result.name"></li>
        </ul>
    </div>
</template>
<script>
export default {
    data() {
        return {
            keywords: null,
            results: []
        };
    },
    watch: {
        keywords(after, before) {
            this.fetch();
        }
    },
    methods: {
        fetch() {
            axios.get('/res-search', { params: { keywords: this.keywords } })
                .then(response => this.results = response.data)
                .catch(error => {});
        }
    }
}
</script>

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

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

Step 9: Create Blade Views And Initialize Vue Components

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 your 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 10 Vue JS Live Search 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 create one file name search.blade.php. Then update the following code into your search.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 Live Search</div>
                    
                <div class="card-body">
                  <search-component></search-component>
                </div>
                
            </div>
        </div>
    </div>
</div>
@endsection 

Step 10: Run Development Server

Now, execute the following command on terminal to start the development server:

npm run dev
or 
npm run watch

Conclusion

In this live search in Vue js laravel app example tutorial, you have learned how to implement live search functionality on blogs posts with Vue js in laravel apps.

Recommended Laravel Vue Js Posts

Recommended:- Laravel Try Catch

AuthorAdmin

My name is Devendra Dode. I am a full-stack developer, entrepreneur, and owner of Tutsmake.com. I like writing tutorials and tips that can help other developers. I share tutorials of PHP, Python, Javascript, JQuery, Laravel, Livewire, Codeigniter, Node JS, Express JS, Vue JS, Angular JS, React Js, MySQL, MongoDB, REST APIs, Windows, Xampp, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL and Bootstrap from a starting stage. As well as demo example.

Leave a Reply

Your email address will not be published. Required fields are marked *