Create a real-time search in Laravel 8 & Ajax

Muhammed ElFeqy
4 min readFeb 13, 2021

Introduction

After inserting a bunch of data, and having a huge data in your database table. in most cases you’ll need to create a search functionality to make it easy for the user to find specific records.

so the best way to do that is by using ajax to make the request happens in real-time.

that’s why we’ll figure out how to create a simple search functionality using Laravel 8 & Ajax.

you can find all the article’s project files in Github.

so, how to implement this functionality in laravel?

well, it’s quite easy, just follow these steps.

1. Install Laravel

  • first of all, you need to create a brand new laravel app (optional), so open your terminal and run the following commands.
composer create-project laravel/laravel laravel-searchcd laravel-searchphp artisan serve

2. Add your database credentials in the .env file.

make sure to add the right credentials according to your settings.

DB_CONNECTION=mysqlDB_HOST=127.0.0.1DB_PORT=3306DB_DATABASE=laravel_searchDB_USERNAME=rootDB_PASSWORD=

3. Create Model, Migration, Factory, And Controller

now you have to create the Post Model (for example), migration, Factory, and controller.

well, we can create all this by executing this command:

php artisan make:model Post -mfc
  • -m: tells the artisan to create the migration file.
  • -f: the factory file.
  • -c: our model controller.

now navigate to database > migrations> 00_0_0_0_create_posts_table.php, and add your fields to theschema ‘s callback.

Schema::create('posts', function (Blueprint $table){$table->id();$table->string('title');$table->text('description');$table->timestamps();});

now go to app > Models > Post.php and add the assignable fields:

class Post extends Model{use HasFactory;protected $fillable = ['title', 'description'];
}

we can shorten the time by inserting a bunch of data using factory what we just created.

head to database > factories > PostFactory.php

add a fack data as follow :

public function definition(){return['title'         => $this->faker->sentence,'description'   => $this->faker->paragraph(5),];}

we’re using laravel 8 for this article, so if you’re using an older version you have to go and check out how factories work in your app version

in your DatabaseSeeder.php we’ll add the following line:

public function run(){// \App\Models\User::factory(10)->create();Post::factory(50)->create();}

now we’ll migrate our database and insert some data in our post table:

php artisan migrate --seed

after that, got to your controller in app > Http > Controllers > PostsController.php.

use App\Models\Post;use Illuminate\Http\Request;class PostController extends Controller{public function index(){return view('posts.index');}public function search(Request $request){$results = Post::where('title', 'LIKE', "%{$request->search}%")->get();return view('posts.results', compact('results'))->with(['search' => $request->search])->render();}public function show(Request $request){$post = Post::findOrFail($request->id);return view('posts.post', compact('post'))->render();}}

4. Configure your routes.

to configure your app routes, navigate to routes > web.php.

Route::get('posts',[PostController::class, 'index'])->name('posts.index');Route::get('posts/search',[PostController::class, 'search'])->name('posts.search');Route::get('posts/show',[PostController::class, 'show'])->name('posts.show');

5. Create views files

we have a three-view file.

  1. index.blade.php, is our main view.
  2. results.blade.php, is for rendering the results and send them to the view.
  3. post.blade.php, is for showing a particular single post.

head to resources > view > posts and create the blade files with the following code:

6.add some styles to your view to make it much nicer and cleaner (Optional).

in main.css file:

#search-wrapper {position: relative;}#search-wrapper #results{height: auto;max-height: 200px;overflow-y: scroll;position: absolute;top: 38px;left: 0;background: #fff;width: 100%;border: 1px solid #eee;border-top: none;border-radius: 5px;margin: 0 11px;}#search-wrapper #results ul li{width: 100%;border-bottom: 1px solid #333;}#search-wrapper #results ul li:last-child {border-bottom: none;}#search-wrapper #results ul li a{display: block;padding: 10px 20px;color: #333;text-decoration: none;}

7. test your final result.

congratulations, now you have accomplished your goal to create a real-time search functionality in your app.

The DEMO.

if you have any question, just comment it below or contact me directly on Twitter it will be an honor to help you.

#keep_coding

--

--

Muhammed ElFeqy

Hello devs👋, I’m a developer sharing my thoughts (📝) during my journey as a developer. so, let’s </code>.