article

Friday, April 22, 2022

Laravel 9 Search using AJAX

Laravel 9 Search using AJAX
Bootstrap 5
https://getbootstrap.com/docs/5.0/getting-started/introduction/
https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css

Jquery
https://jquery.com/download/
CDN : jsDelivr CDN
https://www.jsdelivr.com/package/npm/jquery
https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js

How to install laravel 9

https://tutorial101.blogspot.com/2022/02/how-to-install-laravel-9.html

Connecting our Database

open .env file root directory. 

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

Creating Controller

php artisan make:controller MemberController
C:\xampp\htdocs\laravel9\blog>php artisan make:controller MemberController
change it with the following codes:
blog\app\Http\Controllers\MemberController.php
//blog\app\Http\Controllers\MemberController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Member; //add members Model

class MemberController extends Controller
{
    public function index(){
    	$members = Member::all();
    	return view('search')->with('members', $members);
    }
 
    public function search(Request $request){
    	$search = $request->input('search');
 
	    $members = Member::where('firstname', 'like', "$search%")
	       ->orWhere('lastname', 'like', "$search%")
	       ->get();
 
	    return view('result')->with('members', $members);
    }
 
    public function viewmember($id){
 
        $member = Member::find($id);
 
        return view('member')->with('member', $member);
    }
 
    public function find(Request $request){
        $search = $request->input('search');
 
        $members = Member::where('firstname', 'like', "$search%")
           ->orWhere('lastname', 'like', "$search%")
           ->get();
 
        return view('searchresult')->with('members', $members);
    }
}
Creating Model
php artisan make:model Member -m
C:\xampp\htdocs\laravel9\blog>php artisan make:model Member -m

This will create our model in the form of File.php file located : blog\app\Models\Member.php

we put -m when we create our model.
this will automatically make the migration for our model and you will see that in yourproject/database/migrations
blog\database\migrations\create_members_table.php
edit code blog\database\migrations\create_members_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('members', function (Blueprint $table) {
            $table->increments('id');
            $table->string('firstname');
            $table->string('lastname');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('members');
    }
};
Database Migration
php artisan migrate

C:\xampp\htdocs\laravel9\blog>php artisan migrate
Migration table created successfully.
check database table

Creating Routes
blog\routes\web.php
//blog\routes\web.php
<?php
use Illuminate\Support\Facades\Route;

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

Route::get('/', 'MemberController@index');
Route::get('/search','MemberController@search');
Route::get('/member/{id}','MemberController@viewmember');
Route::post('/find','MemberController@find');
Creating Views
blog\resources\views\app.blade.php
//blog\resources\views\app.blade.php
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="csrf-token" content="{{ csrf_token() }}">
<title>Laravel Search using AJAX - cairocoders</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" />
<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
<style>
@import url("https://fonts.googleapis.com/css2?family=Poppins:weight@100;200;300;400;500;600;700;800&display=swap");
body {
    background-color: #eee;
    font-family: "Poppins", sans-serif;
    font-weight: 300
}
.height {
    height: 100vh
}
.search {
    position: relative;
    box-shadow: 0 0 40px rgba(51, 51, 51, .1)
}
.search input {
    height: 60px;
    text-indent: 25px;
    border: 2px solid #d6d4d4
}
.search input:focus {
    box-shadow: none;
    border: 2px solid blue
}
.search button {
    position: absolute;
    top: 5px;
    right: 5px;
    height: 50px;
    width: 110px;
    background: blue
}
</style>
</head>
<body>
<div class="container">
    <div class="row justify-content-center align-items-center">
        <div class="col-md-8">
			<h2 class="page-header text-center">Laravel 9 Search using AJAX</h2>
            <div class="search"> <i class="fa fa-search"></i> 
			<form class="navbar-form navbar-left" action="{{ URL::to('find') }}" method="POST">
    		    {{ csrf_field() }}
    		        <input type="text" id="search" name="search" class="form-control" placeholder="Search Member" autocomplete="off">
					<button type="submit" class="btn btn-primary">Search</button> 
    		</form>
			</div>
            
			<div id="result" class="panel panel-default" style="display:none">
				<ul class="list-group" id="memList">
				
				</ul>
			</div>
		</div>
		
		@yield('content')
		
    </div>
</div>
<script type="text/javascript">
$(document).ready(function(){
    $.ajaxSetup({
    	headers: {
    		'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    	}
    });
     
    $('#search').keyup(function(){
    	var search = $('#search').val();
    	if(search==""){
    		$("#memList").html("");
    		$('#result').hide();
    	}
    	else{
    		$.get("{{ URL::to('search') }}",{search:search}, function(data){
    			$('#memList').empty().html(data);
    			$('#result').show();
    		})
    	}
    });
});
</script>
</body>
</html>
blog\resources\views\search.blade.php
//blog\resources\views\search.blade.php
    @extends('app')
     
    @section('content')
    	<div class="col-md-8">
    		<h4>Members Table</h4>
    		<table class="table table-bordered table-striped">
    			<thead>
    				<th>Firstname</th>
    				<th>Lastname</th>
    			</thead>
    			<tbody>
    				@foreach($members as $member)
    					<tr>
    						<td>{{$member->firstname}}</td>
    						<td>{{$member->lastname}}</td>
    					</tr>
    				@endforeach
    			</tbody>
    		</table>
    	</div>
    @endsection
blog\resources\views\result.blade.php
//blog\resources\views\result.blade.php
	@if(count($members) > 0)
    	@foreach($members as $member)
    		<li class="list-group-item"><a href="{{ url('member/'.$member->id) }}">{{ $member->firstname }} {{ $member->lastname }}</a></li>
    	@endforeach
    @else
    	<li class="list-group-item">No Results Found</li>
    @endif
blog\resources\views\search.blade.php
//blog\resources\views\search.blade.php
    @extends('app')
     
    @section('content')
    	<div class="col-md-8">
    		<h4>Members Table</h4>
    		<table class="table table-bordered table-striped">
    			<thead>
    				<th>Firstname</th>
    				<th>Lastname</th>
    			</thead>
    			<tbody>
    				@foreach($members as $member)
    					<tr>
    						<td>{{$member->firstname}}</td>
    						<td>{{$member->lastname}}</td>
    					</tr>
    				@endforeach
    			</tbody>
    		</table>
    	</div>
    @endsection
blog\resources\views\searchresult.blade.php
//blog\resources\views\searchresult.blade.php
    @extends('app')
     
    @section('content')
    	@if(count($members) > 0)
    		<h2>Search Results</h2>
    		<ul class="list-group">
    			@foreach($members as $member)
    				<li class="list-group-item"><a href="{{ url('member/'.$member->id) }}">{{ $member->firstname }} {{ $member->lastname }}</a></li>
    			@endforeach
    		</ul>
    	@else
    		<h2>No Results Found</h2>
    	@endif
    @endsection
Edit RouteServiceProvider.php
blog\app\Providers\RouteServiceProvider.php
uncomment protected $namespace = 'App\\Http\\Controllers';

Run C:\xampp\htdocs\laravel9\blog>php artisan serve
Starting Laravel development server: http://127.0.0.1:8000

Related Post