Ajax multiple searching from database using ajax in laravel 11

 <?php


namespace App\Http\Controllers;

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

class SearchController extends Controller
{
    public function search(Request $request)
    {
        $query = User::query();

        if ($request->ajax()) {
            $users = $query->where("name", "LIKE", "%" . $request->search . "%")
                ->orWhere("email", "LIKE", "%" . $request->search . "%")
                ->orWhere("mno", "LIKE", "%" . $request->search . "%")
                ->get();
            return response()->json(["users" => $users]);
        } else {
            $users = $query->get();
            return view("search", compact("users"));
        }
    }
}
Above File is app\Http\Controllers\SearchController.php File





Below File is app\Models\User.php File
<?php

namespace App\Models;

// use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class User extends Authenticatable
{
    /** @use HasFactory<\Database\Factories\UserFactory> */
    use HasFactory, Notifiable;
    public $timestamps = false;
    protected $table = "users";

    /**
     * The attributes that are mass assignable.
     *
     * @var list<string>
     */
    protected $fillable = [
        'name',
        'email',
        'mno',
    ];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var list<string>
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * Get the attributes that should be cast.
     *
     * @return array<string, string>
     */
    protected function casts(): array
    {
        return [
            'email_verified_at' => 'datetime',
            'password' => 'hashed',
        ];
    }
}





Below File is database\json\users.json File
[
    {
        "name": "Sandeep",
        "email": "sandeep@gmail.com",
        "mno": "9833478861"
    },
    {
        "name": "Kuldeep",
        "email": "kuldeep@gmail.com",
        "mno": "4599807762"
    },
    {
        "name": "Neha",
        "email": "neha@gmail.com",
        "mno": "7633290087"
    },
    {
        "name": "Rahul",
        "email": "rahul@gmail.com",
        "mno": "6288976604"
    },
    {
        "name": "Kamna",
        "email": "kamna@gmail.com",
        "mno": "8799034456"
    },
    {
        "name": "Lokhande",
        "email": "lokhande@gmail.com",
        "mno": "8799839233"
    }
]






Below File is database\migrations\2025_01_03_055448_create_users_table File
<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string("name");
            $table->string("email");
            $table->string("mno");
        });
    }

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






Below File is database\seeders\DatabaseSeeder.php File
<?php

namespace Database\Seeders;

use App\Models\User;
// use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    /**
     * Seed the application's database.
     */
    public function run(): void
    {
        // User::factory(10)->create();

        // User::factory()->create([
        //     'name' => 'Test User',
        //     'email' => 'test@example.com',
        // ]);

        $this->call([
            UserSeeder::class
        ]);
    }
}





Below File is database\seeders\UserSeeder.php File
<?php

namespace Database\Seeders;

use App\Models\User;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\File;

class UserSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        $json = File::get(path: "database/json/users.json");
        $user = collect(json_decode($json));

        $user->each(function ($user) {
            User::create([
                "name" => $user->name,
                "email" => $user->email,
                "mno" => $user->mno
            ]);
        });
    }
}






Below File is resources\views\search.blade.php File
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF_8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Search</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-YvpcrYf0tY3lHB60NNkmXc5s9fDVZLESaAA55NDzOxhy9GkcIdslK1eN7N6jIeHz" crossorigin="anonymous"></script>
    <script src="https://code.jquery.com/jquery-3.7.1.min.js" integrity="sha256-/JqT3SQfawRcv/BIHPThkBvs0OEvtFFmqPF/lYI/Cxo=" crossorigin="anonymous"></script>
</head>
<body>
    <div class="container">
        <div class="row justify-content-center">
            <div class="col-10">
                <div class="card">
                    <div class="card-header">
                        <h2>Search Here</h2>
                    </div>
                    <div class="card-body">
                        <input type="search" name="search" class="form-control" id="search" placeholder="Search here..."/><br><br>
                        <table class="table table-bordered table-striped table-hovered">
                            <thead>
                                <th>ID</th>
                                <th>Name</th>
                                <th>Email</th>
                                <th>Mobile No.</th>
                            </thead>
                            <tbody id="tbody">
                                @if(count($users) > 0)
                                    @foreach($users as $data)
                                        <tr>
                                            <td>{{ $data->id }}</td>
                                            <td>{{ $data->name }}</td>
                                            <td>{{ $data->email }}</td>
                                            <td>{{ $data->mno }}</td>
                                        </tr>
                                    @endforeach
                                @else
                                    <tr>
                                        <td>No user found</td>
                                    </tr>
                                @endif
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        $(document).ready(function(){
            $("#search").on("keyup",function(){
                var value = $(this).val();
                $.ajax({
                    url:"{{ route('userSearch') }}",
                    type:"GET",
                    data:{"search":value},
                    success:function(data){
                        var users = data.users;
                        var html = "";
                        if(users.length > 0) {
                            for(let i=0;i<users.length;i++) {
                                html += '<tr>\
                                    <td>'+users[i]["id"]+'</td>\
                                    <td>'+users[i]["name"]+'</td>\
                                    <td>'+users[i]["email"]+'</td>\
                                    <td>'+users[i]["mno"]+'</td>\
                                    </tr>';
                            }

                        } else {
                            html += '<tr>\
                                    <td colspan="4">No users found</td>\
                                </tr>';
                        }
                        $("#tbody").html(html);
                    }
                });
            });
        });
    </script>
</body>
</html>





Below File is routes\web.php File
<?php

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

Route::get('/', function () {
    return view('welcome');
});

Route::controller(SearchController::class)->group(function () {
    Route::get("/user-search", "search")->name("userSearch");
});









Comments

Popular posts from this blog

Eloquent Many to Many Relationship Tutorial in Laravel 11

Eloquent with JSON Data Columns Tutorial in Laravel 11

Blade Template Tutorial Three Template Inheritance in Laravel 11