Laravel 9 live search data using ajax - WebJourney

Laravel 9 live search data using ajax - WebJourney

Hello coders, welcome again with me in this new tutorial we will learn about laravel live search system step by step using ajax. You will learn how to create a real time data search in a table without any page loading. For this we have the following steps.

 

1. Install a new project 

2. Create database and connect

3. Create model and migration

4. Create routes

5. Create Controller

6. Create blade view

7. Start server and test

 

1. Install a new project 

 

If you already have a fresh project install just skip this step or you will creata a new project using composer.

//By composer
composer create-project laravel/laravel live-search

 

2. Create database and connect

 

Now we have to create our database live_search and connect it to the application. After create  the database open .env file and put all database info database name, user name and password. if you have not any password keep this blank show in bellow.

.env

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

 

3. Create model and migration

 

Now we will create a model LiveSearch with migration file using artisan command.

php artisan make:model LiveSearch -m

Once tha model and migration have completed open 2022_08_20_073349_create_live_searches_table.php migration file in your editor and add required column name.

2022_08_20_073349_create_live_searches_table.php

<?php

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

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

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

 

Now run migrate command

php artisan migrate

Open your model from App\Models\LiveSearch.php and create a protected $fillable array variable.

App\Models\LiveSearch.php

<?php

namespace App\Models;

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

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

 

Ok, Lets insert some dummy data into our table live_searches using factory or you can insert data manually. For testing purpose I insert some data manually.

 

4. Create routes

 

We will create two routes in web.php, one is for displaying data in table and another one is for live searching.

routes\web.php

<?php

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


Route::get('/',[LiveSearchController::class,'show_data'])->name('show.data');
Route::get('/live-search',[LiveSearchController::class,'live_search'])->name('live.search');

 

5. Create Controller

 

Create controller LiveSearchController and implements real time search logic.

php artisan make:controller LiveSearchController

 

LiveSearchController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\LiveSearch;

class LiveSearchController extends Controller
{
    public function show_data(Request $request)
    {
        $records = LiveSearch::latest()->get();
        return view('welcome',compact('records'))->render();
    }

    //search product 
    public function live_search(Request $request)
    {
        $records = LiveSearch::where('title', 'like', '%'.$request->search_string.'%')
        ->orWhere('description', 'like', '%'.$request->search_string.'%')
        ->orderBy('id','desc')->get();

        if($records->count() >= 1){
            return view('search_result',compact('records'))->render();
        }else{
            return response()->json([
                'status'=>'nothing_found',
            ]);
        }
    }
}

 

6. Create blade file

 

Inside resources\views directory we will create a new blade file search_result.blade.php.  Bellow our two view files with code example. Copy and paste the codes inside your files.

 

welcome.blade.php

<!doctype html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
     <meta name="csrf-token" content="{{ csrf_token() }}">
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <title>Laravel Live search-Webjourney</title>
  </head>
  <body>
      <div class="container">
          <div class="row">
              <div class="col-md-2"></div>
              <div class="col-md-8">
                  <h2 class="my-5 text-center">Laravel 9 Live Search With Ajax</h2>
                  <input type="text" name="search" id="search" class="mb-3 form-control" placeholder="Search Here...">
                  <div class="table-data">
                    <table class="table table-bordered">
                        <thead>
                          <tr>
                            <th scope="col">#</th>
                            <th scope="col">Title</th>
                            <th scope="col">Description</th>
                          </tr>
                        </thead>
                        <tbody>
                            @foreach($records as $key=>$rec)
                              <tr>
                                <th>{{ $key+1 }}</th>
                                <td>{{ $rec->title }}</td>
                                <td>{{ $rec->description }}</td>
                              </tr>
                            @endforeach
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });
</script>
<script type="text/javascript">
     //search record 
    $(document).on('keyup',function(e){
        e.preventDefault();
        let search_string = $('#search').val();
        $.ajax({
            url:"{{ route('live.search') }}",
            method:'GET',
            data:{search_string:search_string},
            success:function(res){
                $('.table-data').html(res);
                if(res.status=='nothing_found'){
                    $('.table-data').html('<span class="text-danger">'+'Nothing Found'+'</span>');
                }
            }
        });
    })

</script> 

</body>
</html>

 

search_result.blade.php

<table class="table table-bordered">
    <thead>
      <tr>
        <th scope="col">#</th>
        <th scope="col">Title</th>
        <th scope="col">Description</th>
      </tr>
    </thead>
    <tbody>
        @foreach($records as $key=>$rec)
          <tr>
            <th>{{ $key+1 }}</th>
            <td>{{ $rec->title }}</td>
            <td>{{ $rec->description }}</td>
          </tr>
        @endforeach
    </tbody>
</table>

 

7. Start server and test application

 

Now run development server using the artisan command and test your application.

php artisan serve

 

Hope this will helps you. Thanks

 

If you like what you are reading, please think about buying us a coffee as a token of appreciation.

Buy Me A Coffee

We appreciate your support and are committed to providing you useful and informative content.

We are thankful for your ongoing support 

Tags

  • Share This: