Laravel: Search using AJAX
Submitted by nurhodelta_17 on Thursday, November 23, 2017 - 14:08.
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:- <?php
- namespace App\Http\Controllers;
- use Illuminate\Http\Request;
- use App\Member;
- 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 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:- <?php
- use Illuminate\Support\Facades\Schema;
- use Illuminate\Database\Schema\Blueprint;
- use Illuminate\Database\Migrations\Migration;
- class CreateMembersTable 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');
- }
- }
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); 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:- <?php
- Route::get('/', 'MemberController@index');
- Route::get('/search','MemberController@search');
- Route::get('/member/{id}','MemberController@viewmember');
- Route::post('/find','MemberController@find');
Creating our Views
In resources/views folder, create the ff files: app.blade.php- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="UTF-8">
- <meta name="csrf-token" content="{{ csrf_token() }}">
- <title>Laravel: Search using AJAX</title>
- <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
- <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
- <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
- </head>
- <body>
- @include('navbar')
- <div id="result" class="panel panel-default" style="width:400px; position:absolute; left:180px; top:55px; z-index:1; display:none">
- <ul style="margin-top:10px; list-style-type:none;" id="memList">
- </ul>
- </div>
- <div class="container">
- @yield('content')
- </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){
- $('#result').show();
- })
- }
- });
- });
- </script>
- </body>
- </html>
- <nav class="navbar navbar-default">
- <div class="container-fluid">
- <!-- Brand and toggle get grouped for better mobile display -->
- <div class="navbar-header">
- <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
- </button>
- </div>
- <!-- Collect the nav links, forms, and other content for toggling -->
- <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
- <form class="navbar-form navbar-left" action="{{ URL::to('find') }}" method="POST">
- {{ csrf_field() }}
- <div class="input-group">
- <input type="text" id="search" name="search" class="form-control" placeholder="Search Member">
- <span class="input-group-btn">
- <button type="submit" class="btn btn-default">
- </button>
- </span>
- </div>
- </form>
- </div><!-- /.navbar-collapse -->
- </div><!-- /.container-fluid -->
- </nav>
- @extends('app')
- @section('content')
- <div class="row">
- <div class="col-md-8 col-md-offset-2">
- <h2 class="page-header text-center">Search using AJAX</h2>
- <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>
- </div>
- @endsection
- @extends('app')
- @section('content')
- <div class="row">
- <h2>{{ $member->firstname }} {{ $member->lastname }}</h2>
- <a href="/" class="btn btn-primary"><span class="glyphicon glyphicon-arrow-left"></span> Home</a>
- </div>
- @endsection
- @extends('app')
- @section('content')
- <h2>Search Results</h2>
- <ul style="list-style-type:none;">
- @foreach($members as $member)
- <li><a href="{{ url('member/'.$member->id) }}">{{ $member->firstname }} {{ $member->lastname }}</a></li>
- @endforeach
- </ul>
- @else
- <h2>No Results Found</h2>
- @endif
- @endsection
- @foreach($members as $member)
- <li><a href="{{ url('member/'.$member->id) }}">{{ $member->firstname }} {{ $member->lastname }}</a></li>
- @endforeach
- @else
- <li>No Results Found</li>
- @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
- 574 views