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
How to Disable Right Click using jQuery
How to Disable Right Click usi...

In this small post i will show you how to disable right click using jquery. Here, we will disable right click on pa...

Read More

Aug-18-2021

Laravel 8 User Roles and Permissions Without Package
Laravel 8 User Roles and Permi...

In this tutorial we will see laravel 8 user roles and permissions without package.Roles and permissions are an impo...

Read More

Sep-13-2021

How To Create Web Notifications In Laravel 9 Using Pusher
How To Create Web Notification...

In this article, we will see how to create web notifications in laravel 9 using pusher. Here, we will learn how to...

Read More

Feb-03-2023

Introduction of Node.js Modules
Introduction of Node.js Module...

In this tutorial I will give you information about Introduction of Node.js Modules. Node.js modules provide a way t...

Read More

Sep-10-2021