Laravel: Search using AJAX

Getting Started

First, we're going to create a new project and I'm gonna name it search and add it to localhost with the name search.dev. If you have no idea on how to do this, please refer to my tutorial Installing Laravel - PHP Framework.

Setting up our Database

1. Open your phpMyAdmin and create a new database. In my case, I've created a database named search. 2. In our project, open .env file and update the ff lines depending on your setting. DB_DATABASE=search DB_USERNAME=root DB_PASSWORD=

Creating our Controller

1. In command prompt, navigate to your project and type: php artisan make:controller MemberController This will create our controller in the form of MemberController.php located in app/Http/Controllers folder. 2. Open MemberController.php and edit it with the ff codes:
  1. <?php
  2.  
  3. namespace App\Http\Controllers;
  4.  
  5. use Illuminate\Http\Request;
  6. use App\Member;
  7.  
  8. class MemberController extends Controller
  9. {
  10.     public function index(){
  11.         $members = Member::all();
  12.         return view('search')->with('members', $members);
  13.     }
  14.  
  15.     public function search(Request $request){
  16.         $search = $request->input('search');
  17.  
  18.             $members = Member::where('firstname', 'like', "$search%")
  19.                ->orWhere('lastname', 'like', "$search%")
  20.                ->get();
  21.  
  22.             return view('result')->with('members', $members);
  23.     }
  24.  
  25.     public function viewmember($id){
  26.  
  27.         $member = Member::find($id);
  28.  
  29.         return view('member')->with('member', $member);
  30.     }
  31.  
  32.     public function find(Request $request){
  33.         $search = $request->input('search');
  34.  
  35.         $members = Member::where('firstname', 'like', "$search%")
  36.            ->orWhere('lastname', 'like', "$search%")
  37.            ->get();
  38.  
  39.         return view('searchresult')->with('members', $members);
  40.     }
  41. }

Creating our Model

1. In command prompt, navigate to our project and type: php artisan make:model Member -m This will create our model Member.php located in app folder. It will also create the migration for us due to the -m that we added in creating the model in the form of, in my case 2017_11_22_032430_create_members_table.php file located in database/migrations folder. 2. Open 2017_11_22_032430_create_members_table.php and edit it with ff codes:
  1. <?php
  2.  
  3. use Illuminate\Support\Facades\Schema;
  4. use Illuminate\Database\Schema\Blueprint;
  5. use Illuminate\Database\Migrations\Migration;
  6.  
  7. class CreateMembersTable extends Migration
  8. {
  9.     /**
  10.      * Run the migrations.
  11.      *
  12.      * @return void
  13.      */
  14.     public function up()
  15.     {
  16.         Schema::create('members', function (Blueprint $table) {
  17.             $table->increments('id');
  18.             $table->string('firstname');
  19.             $table->string('lastname');
  20.             $table->timestamps();
  21.         });
  22.     }
  23.  
  24.     /**
  25.      * Reverse the migrations.
  26.      *
  27.      * @return void
  28.      */
  29.     public function down()
  30.     {
  31.         Schema::dropIfExists('members');
  32.     }
  33. }

Migrating

In command prompt, navigate to your project and type: php artisan migrate It will then create our database migration. [Illuminate\Database\QueryException] SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was t oo long; max key length is 767 bytes (SQL: alter table `users` add unique ` users_email_unique`(`email`)) You can solve this by opening AppServiceProvider.php located in app/Providers folder. Add this line: use Illuminate\Support\Facades\Schema; In boot add this line: Schema::defaultStringLength(191); migration error Run php artisan migrate again and make sure that your database is empty because it will have another error if its not.

Creating our Routes

In routes folder, open web.php and edit it with the ff codes:
  1. <?php
  2. Route::get('/', 'MemberController@index');
  3.  
  4. Route::get('/search','MemberController@search');
  5.  
  6. Route::get('/member/{id}','MemberController@viewmember');
  7.  
  8. Route::post('/find','MemberController@find');

Creating our Views

In resources/views folder, create the ff files: app.blade.php
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4.         <meta charset="UTF-8">
  5.         <meta name="csrf-token" content="{{ csrf_token() }}">
  6.         <title>Laravel: Search using AJAX</title>
  7.         <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
  8.         <link rel="stylesheet" href="/css/app.css">
  9.         <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
  10.         <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
  11. </head>
  12. <body>
  13. @include('navbar')
  14.  
  15. <div id="result" class="panel panel-default" style="width:400px; position:absolute; left:180px; top:55px; z-index:1; display:none">
  16.         <ul style="margin-top:10px; list-style-type:none;" id="memList">
  17.                
  18.         </ul>
  19. </div>
  20. <div class="container">
  21.         @yield('content')
  22.  
  23. </div>
  24. <script type="text/javascript">
  25.         $(document).ready(function(){
  26.                 $.ajaxSetup({
  27.                         headers: {
  28.                             'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
  29.                         }
  30.                 });
  31.  
  32.                 $('#search').keyup(function(){
  33.                         var search = $('#search').val();
  34.                         if(search==""){
  35.                                 $("#memList").html("");
  36.                                 $('#result').hide();
  37.                         }
  38.                         else{
  39.                                 $.get("{{ URL::to('search') }}",{search:search}, function(data){
  40.                                         $('#memList').empty().html(data);
  41.                                         $('#result').show();
  42.                                 })
  43.                         }
  44.                 });
  45.         });
  46. </script>
  47. </body>
  48. </html>
narbar.blade.php
  1.         <nav class="navbar navbar-default">
  2.                 <div class="container-fluid">
  3.             <!-- Brand and toggle get grouped for better mobile display -->
  4.                 <div class="navbar-header">
  5.                         <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
  6.                                 <span class="sr-only">Toggle navigation</span>
  7.                                 <span class="icon-bar"></span>
  8.                                 <span class="icon-bar"></span>
  9.                                 <span class="icon-bar"></span>
  10.                         </button>
  11.                         <a class="navbar-brand" href="#">SourceCodester</a>
  12.                 </div>
  13.  
  14.             <!-- Collect the nav links, forms, and other content for toggling -->
  15.                     <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
  16.                         <form class="navbar-form navbar-left" action="{{ URL::to('find') }}" method="POST">
  17.                                 {{ csrf_field() }}
  18.                                 <div class="input-group">
  19.                                         <input type="text" id="search" name="search" class="form-control" placeholder="Search Member">
  20.                                         <span class="input-group-btn">
  21.                                         <button type="submit" class="btn btn-default">
  22.                                         <span class="glyphicon glyphicon-search"></span>
  23.                                         </button>
  24.                                 </span>
  25.                                 </div>
  26.                         </form>
  27.                     </div><!-- /.navbar-collapse -->
  28.           </div><!-- /.container-fluid -->
  29.         </nav>
search.blade.php
  1. @extends('app')
  2.  
  3. @section('content')
  4. <div class="row">
  5.         <div class="col-md-8 col-md-offset-2">
  6.                 <h2 class="page-header text-center">Search using AJAX</h2>
  7.                 <h4>Members Table</h4>
  8.                 <table class="table table-bordered table-striped">
  9.                         <thead>
  10.                                 <th>Firstname</th>
  11.                                 <th>Lastname</th>
  12.                         </thead>
  13.                         <tbody>
  14.                                 @foreach($members as $member)
  15.                                         <tr>
  16.                                                 <td>{{$member->firstname}}</td>
  17.                                                 <td>{{$member->lastname}}</td>
  18.                                         </tr>
  19.                                 @endforeach
  20.                         </tbody>
  21.                 </table>
  22.         </div>
  23. </div>
  24. @endsection
member.blade.php
  1. @extends('app')
  2.  
  3. @section('content')
  4. <div class="row">
  5.         <h2>{{ $member->firstname }} {{ $member->lastname }}</h2>
  6.         <a href="/" class="btn btn-primary"><span class="glyphicon glyphicon-arrow-left"></span> Home</a>
  7. </div>
  8. @endsection
searchresult.blade.php
  1. @extends('app')
  2.  
  3. @section('content')
  4.         @if(count($members) > 0)
  5.                 <h2>Search Results</h2>
  6.                 <ul style="list-style-type:none;">
  7.                         @foreach($members as $member)
  8.                                 <li><a href="{{ url('member/'.$member->id) }}">{{ $member->firstname }} {{ $member->lastname }}</a></li>
  9.                         @endforeach
  10.                 </ul>
  11.         @else
  12.                 <h2>No Results Found</h2>
  13.         @endif
  14. @endsection
result.blade.php
  1. @if(count($members) > 0)
  2.         @foreach($members as $member)
  3.                 <li><a href="{{ url('member/'.$member->id) }}">{{ $member->firstname }} {{ $member->lastname }}</a></li>
  4.         @endforeach
  5. @else
  6.         <li>No Results Found</li>
  7. @endif

Running our Server

In your web browser, type the name that you added in localhost for your project in my case, search.dev. That ends this tutorial. Happy Coding :)

Add new comment