Laravel is my favorite framework that I use for web application development. So I started this Laravel article series to share my experience with you guys! Now this article series is getting more views and popular! As another article to the series, I'll do another interesting tutorial on a very familiar thing when you surf through web sites. You may have seen that many sites have a search bar which displays the search results real time, when we type something in the search box. It's a enhancement for user experience. But how to implement this? Only Laravel can do it? No..We need real time mechanism! So, Laravel + Javascript do the job!
Target : To fetch some countries from database and display the names real time
Step 1 - Create new laravel project
composer create-project laravel/laravel LaravelSearch
Step 2 - Configure database
Open the project in a text editor and edit database configuration files.
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Schema;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
Schema::defaultStringLength(191);
}
/**
* Register any application services.
*
* @return void
*/
public function register()
{
//
}
}
NOTE :
Delete the migrations in database/migrations built automatically called password resets and users. We don't need them. We are going to create a new model and a migration file. Open a command prompt/terminal and go into the project. Then type the below command to create a model.
php artisan make:model Country -m
Now there will a model called Country and a migration file made for countries in database/migrations folder. Open the migration file to edit.
database/migrations/migration.php
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateCountriesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('countries', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('code');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('countries');
}
}
Now we are ready to migrate our database. Then a table called countries will be created. Command to migrate :
php artisan migrate
Next step is to seed the data to the database using this seeder file. Open DatabaseSeeder.php file in database/seeds folder. Then place this line within run function.
$this->call(CountriesTableSeeder::class);
Open up a terminal and go into the project. Type the below command to run the seeder!
php artisan db:seed
Step 3 - Seed data to the database
Now we need some data to be stored in our database. So, Laravel provides seeding function for this. Create a seeder file called CountriesTableSeeder to seed some countries! Use this command.
php artisan make:seeder CountriesTableSeeder
Then edit the file like this.
<?php
use Illuminate\Database\Seeder;
class CountriesTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$country = new \App\Country([
'name' => 'Sri Lanka',
'code' => 'SL'
]);
$country->save();
$country = new \App\Country([
'name' => 'India',
'code' => 'IND'
]);
$country->save();
$country = new \App\Country([
'name' => 'America',
'code' => 'USA'
]);
$country->save();
$country = new \App\Country([
'name' => 'England',
'code' => 'UK'
]);
$country->save();
$country = new \App\Country([
'name' => 'Singapore',
'code' => 'SIN'
]);
$country->save();
}
}
Next step is to seed the data to the database using this seeder file. Open DatabaseSeeder.php file in database/seeds folder. Then place this line within run function.
$this->call(CountriesTableSeeder::class);
Open up a terminal and go into the project. Type the below command to run the seeder!
php artisan db:seed
Go to resources/views folder and open welcome.blade.php file and place the below code.
NOTE:
There's a script included in the code. This is the main part of our task! This script is explained using comments on the view itself!
<!doctype html>
<html lang="{{ app()->getLocale() }}">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Laravel</title>
<link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<style type="text/css">
body{
font-family: 'Roboto', sans-serif;
}
</style>
</head>
<body>
<div class="container" style="margin-top: 50px;">
<div class="row">
<div class="col-lg-3"></div>
<div class="col-lg-6">
<h4 class="text-center">Autocomplete Search Box with <br> Laravel + Ajax + jQuery</h4><hr>
<div class="form-group">
<label>Type a country name</label>
<input type="text" name="country" id="country" placeholder="Enter country name" class="form-control">
</div>
<div id="country_list"></div>
</div>
<div class="col-lg-3"></div>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
<script type="text/javascript">
// jQuery wait till the page is fullt loaded
$(document).ready(function () {
// keyup function looks at the keys typed on the search box
$('#country').on('keyup',function() {
// the text typed in the input field is assigned to a variable
var query = $(this).val();
// call to an ajax function
$.ajax({
// assign a controller function to perform search action - route name is search
url:"{{ route('search') }}",
// since we are getting data methos is assigned as GET
type:"GET",
// data are sent the server
data:{'country':query},
// if search is succcessfully done, this callback function is called
success:function (data) {
// print the search results in the div called country_list(id)
$('#country_list').html(data);
}
})
// end of ajax call
});
// initiate a click function on each search result
$(document).on('click', 'li', function(){
// declare the value in the input field to a variable
var value = $(this).text();
// assign the value to the search box
$('#country').val(value);
// after click is done, search results segment is made empty
$('#country_list').html("");
});
});
</script>
</body>
</html>
Step 5 - Make a controller to implement the search functionality
Create a new controller using command prompt. Command :
php artisan make:controller SearchController
Then place the code included below. Comments have been put to explain the code to you..Read them!
<?php
namespace App\Http\Controllers;
use App\Country;
use http\Env\Response;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class SearchController extends Controller
{
public function search(Request $request){
// check if ajax request is coming or not
if($request->ajax()) {
// select country name from database
$data = Country::where('name', 'LIKE', $request->country.'%')
->get();
// declare an empty array for output
$output = '';
// if searched countries count is larager than zero
if (count($data)>0) {
// concatenate output to the array
$output = '<ul class="list-group" style="display: block; position: relative; z-index: 1">';
// loop through the result array
foreach ($data as $row){
// concatenate output to the array
$output .= '<li class="list-group-item">'.$row->name.'</li>';
}
// end of output
$output .= '</ul>';
}
else {
// if there's no matching results according to the input
$output .= '<li class="list-group-item">'.'No results'.'</li>';
}
// return output result array
return $output;
}
}
}
Now we are ready to run the project! Enter the command php artisan serve after navigating into the project to run our project. Then open web browser and type localhost:8000 to view the output.
I think you may have this output. If not please check the steps I have completed! Now type anything in the input field. See there is it displaying "No Results" when you type a country name that is not in database? Then type a stored name of a country. You get the list of countries according to your input? If so, you have done the work guys!!! That's all..
This is the way to implement the auto suggest search box using Laravel and JS. Read and learn the way to such things because only Laravel can not cater all the requirements guys!
So, it's time to stop! Good Bye guys!
I think you may have this output. If not please check the steps I have completed! Now type anything in the input field. See there is it displaying "No Results" when you type a country name that is not in database? Then type a stored name of a country. You get the list of countries according to your input? If so, you have done the work guys!!! That's all..
This is the way to implement the auto suggest search box using Laravel and JS. Read and learn the way to such things because only Laravel can not cater all the requirements guys!
So, it's time to stop! Good Bye guys!
Autocomplete Search with Laravel, jQuery and Ajax
Reviewed by DAL
on
September 08, 2018
Rating:
No comments: