Laravel 10 Scout Search and Algolia Example

Websolutionstuff | Feb-21-2024 | Categories : Laravel

Hey everyone! Ever wished your Laravel application could deliver lightning-fast search results? Well, I've got great news for you! In this guide, I'm going to show you how to supercharge your Laravel app's search functionality using Laravel Scout and Algolia.

By the end of this guide, you'll be able to implement advanced search features that provide accurate results at warp speed, making your users' experience on your app smoother and more enjoyable.

So, let's see the laravel 10 Scout search and Algolia example, the Laravel Scout search, how to search using Scout in laravel 8/9/10, algolia search in laravel 9/10, Laravel Scout Algolia.

Step 1: Set Up Your Laravel 10 Project

First things first, let's create a new Laravel project or use an existing one if you have it set up already. Open your terminal and run:

laravel new my-laravel-project

 

Step 2: Install Scout and Algolia

Next, let's install Laravel Scout and Algolia via Composer. In your terminal, navigate to your project directory and run:

composer require laravel/scout algolia/algoliasearch-client-php

 

Step 3: Configure Scout and Algolia

Now, let's configure Scout and Algolia. Add your Algolia credentials to your .env file:

SCOUT_QUEUE=true

ALGOLIA_APP_ID=your_app_id
ALGOLIA_SECRET=your_secret

 

Step 4: Make Migration and Model

Now, let's make migration and models searchable.

php artisan make:migration create_items_table

Migration:

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;


class CreateItemsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('items', function (Blueprint $table) {
           $table->increments('id');
           $table->string('title');
           $table->timestamps();
       });
    }


    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop("items");
    }
}

app/Models/Items.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Laravel\Scout\Searchable;

class Item extends Model
{

    use Searchable;

    public $fillable = ['title'];

    /**
     * Get the index name for the model.
     *
     * @return string
    */
    public function searchableAs()
    {
        return 'items_index';
    }
}

 

Step 5: Add New Route

Now, we'll add routes to the web.php file.

routes/web.php

Route::get('items', 'SearchController@index')->name('items');
Route::post('create-item', 'SearchController@create')->name('create-item');

 

Step 6: Create Controller

After that, we'll create a SearchController.php file using the following command.

app/Http/Controllers/SearchController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests;
use App\Models\Item;


class SearchController extends Controller
{


	/**
     * Get the index name for the model.
     *
     * @return string
    */
    public function index(Request $request)
    {
        if($request->has('title_search')){
            $items = Item::search($request->title_search)->paginate(5);
        }else{
            $items = Item::paginate(6);
        }
        return view('index',compact('items'));
    }


    /**
     * Get the index name for the model.
     *
     * @return string
    */
    public function create(Request $request)
    {
        $this->validate($request,['title'=>'required']);

        $items = Item::create($request->all());
        return back();
    }
}
 
Step 7: Create View

Now, we'll create an index.blade.php file to search records using Scout and Algolia.

resources/views/item-search.blade.php

<!DOCTYPE html>
<html>
	<head>
		<title>Laravel 10 Scout Search and Algolia Example - Websolutionstuff</title>
		<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
	</head>
	<body>
		<div class="container">
			<h2>Laravel 10 Scout Search and Algolia Example - Websolutionstuff</h2>
			<br/>
			<form method="POST" action="{{ route('create-item') }}" autocomplete="off">
				@if(count($errors))
				<div class="alert alert-danger">
					<strong>Whoops!</strong> There were some problems with your input.
					<br/>
					<ul>
						@foreach($errors->all() as $error)
						<li>{{ $error }}</li>
						@endforeach
					</ul>
				</div>
				@endif
				<input type="hidden" name="_token" value="{{ csrf_token() }}">
				<div class="row">
					<div class="col-md-6">
						<div class="form-group {{ $errors->has('title') ? 'has-error' : '' }}">
							<input type="text" id="title" name="title" class="form-control" placeholder="Enter Title" value="{{ old('title') }}">
							<span class="text-danger">{{ $errors->first('title') }}</span>
						</div>
					</div>
					<div class="col-md-6">
						<div class="form-group">
							<button class="btn btn-success">Create New Item</button>
						</div>
					</div>
				</div>
			</form>
			<div class="panel panel-primary">
				<div class="panel-heading">Item management</div>
				<div class="panel-body">
					<form method="GET" action="{{ route('items') }}">
						<div class="row">
							<div class="col-md-6">
								<div class="form-group">
									<input type="text" name="title_search" class="form-control" placeholder="Enter Title For Search" value="{{ old('title_search') }}">
								</div>
							</div>
							<div class="col-md-6">
								<div class="form-group">
									<button class="btn btn-success">Search</button>
								</div>
							</div>
						</div>
					</form>
					<table class="table table-bordered">
						<thead>
							<th>Id</th>
							<th>Title</th>
							<th>Creation Date</th>
							<th>Updated Date</th>
						</thead>
						<tbody>
							@if($items->count())
							@foreach($items as $key => $item)
							<tr>
								<td>{{ ++$key }}</td>
								<td>{{ $item->title }}</td>
								<td>{{ $item->created_at }}</td>
								<td>{{ $item->updated_at }}</td>
							</tr>
							@endforeach
							@else
							<tr>
								<td colspan="4">There are no data.</td>
							</tr>
							@endif
						</tbody>
					</table>
					{{ $items->links() }}
				</div>
			</div>
		</div>
	</body>
</html>

 
Step 8: Test Your Search

That's it! You're ready to test your search functionality. Run your Laravel server:

php artisan serve

To index your data with Algolia, run:

php artisan scout:import "App\Models\Item"

 

Conclusion

Congratulations! You've successfully implemented Scout Search with Algolia in your Laravel application. Now, your users can enjoy lightning-fast and accurate search results.

 


You might also like:

Recommended Post
Featured Post
Integrating ChatGPT with Node and Vue
Integrating ChatGPT with Node...

In a world where technology and human interaction blend seamlessly, artificial intelligence (AI) holds incredible potent...

Read More

Jul-17-2023

Generate Dynamic Sitemap in Laravel
Generate Dynamic Sitemap in La...

Here we will see how to generate dynamic sitemap in laravel. As we know sitemap is very important part of seo, sitemap i...

Read More

Jul-05-2021

How To Add Watermark On Image In Laravel 10
How To Add Watermark On Image...

In this article, we will how to add a watermark to an image in laravel 10. Here we will learn about laravel 10 adding a...

Read More

Mar-31-2023

Load More Data in Laravel Using Ajax jQuery
Load More Data in Laravel Usin...

In this article, we will see example of load more data in laravel using ajax jquery, In many websites, has huge content&...

Read More

Feb-26-2021