Hello Devs,
In this tutorial, we are going to learn search dropdown autocomplete from database in laravel.
Follow this step by step guide given below:
Step 1 :
Install laravel App
composer create-project --prefer-dist laravel/laravel blog
Step 2 :
Create Model and Table
php artisan make:migration create_blogs_table
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateBlogsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('blogs', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('blogs');
}
}
Run this command:
php artisan migrate
app/Blog.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Blog extends Model
{
}
Step 3 :
Create Route routes/web.php
Route::get('search', 'SearchController@index')->name('search');
Route::get('autocomplete', 'SearchController@autocomplete')->name('autocomplete');
Step 4 :
Create Controller app/Http/Controllers/SearchController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Blog;
class SearchController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
return view('search');
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function autocomplete(Request $request)
{
$data = Blog::select("name")
->where("name","LIKE","%{$request->input('query')}%")
->get();
return response()->json($data);
}
}
Step 5 :
Create View File resources/views/search.blade.php
<!DOCTYPE html>
<html>
<head>
<title>Laravel Autocomplete Search From Database - Rathorji.in</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-3-typeahead/4.0.1/bootstrap3-typeahead.min.js"></script>
</head>
<body>
<div class="container">
<h1>Laravel Autocomplete Search From Database - Rathorji.in</h1>
<input class="typeahead form-control" type="text">
</div>
<script type="text/javascript">
var path = "{{ route('autocomplete') }}";
$('input.typeahead').typeahead({
source: function (query, process) {
return $.get(path, { query: query }, function (data) {
return process(data);
});
}
});
</script>
</body>
</html>
Run this command:
php artisan serve
Open this URL:
http://localhost:8000/search
I hope this example helps you.