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
Adding Bootstrap 5 To Angular 15: Step-by-Step Guide
Adding Bootstrap 5 To Angular...

Welcome to my comprehensive step-by-step guide on integrating Bootstrap 5 into Angular 15. As a developer, I understand...

Read More

Jun-12-2023

Laravel 9 whereNull / whereNotNull Query Example
Laravel 9 whereNull / whereNot...

In this article, we will see the laravel 9 whereNull / whereNotNull query example. In laravel 9 additional where clauses...

Read More

Oct-18-2022

How To Create Candlestick Chart In Laravel 9 Using Highcharts
How To Create Candlestick Char...

In this article, we will see how to create a candlestick chart in laravel 9 using highcharts. A candlestick is a ty...

Read More

Oct-06-2022

How to Use Bitmasks for Efficient Data Filtering?
How to Use Bitmasks for Effici...

Data filtering might not sound like the most thrilling topic, but when it comes to processing large volumes of informati...

Read More

Oct-25-2023