Utilizing Laravel Scout to enable Full-Text Search (r)

Share the news on
Since it is an open-source tool, Laravel offers a myriad of out-of-the-box functionalities that enable creators to design effective and efficient applications.
In this piece, we'll explore the tools in depth and demonstrate how ways to incorporate the search function with full text in a Laravel application by using the driver. The model is an Laravel application which will store the names of the mockup trains, and then make use of Laravel Scout to provide an option to search in the application.
The prerequisites
To understand this to follow along, you'll require:
- This PHP compiler is already installed on your system. This tutorial uses PHP Version 8.1.
- The reason for this is Docker Engine, also known as Docker Desktop that you can install on your computer
- An A.Lgolia cloud-based account that you can make for free
What do I need to do to install Scout within a Laravel Project
In order to be able to utilize Scout it is necessary to build an Laravel application that includes the search feature. The Laravel-Scout Bash script includes all the commands required to construct an Laravel application, which is housed within the Docker container. Docker is a fantastic option for developers. Docker indicates that there's no need to install other software including MySQL. MySQL database.
The script Laravel-scout is an example of the Bash programming language. Therefore, you have to execute it in an Linux environment. If you're using Windows Make sure to set up Windows Subsystem in order to switch it over in to Linux (WSL).
If you're using WSL then follow the instructions from your terminal to select your preferred Linux distribution.
WSL --S Ubuntu
After that, you'll need to go to the section in which you'd like to save the project. The script that creates the Laravel-Scout directory will be generated. the project's directory at this point. Here is an example of how the script could create a directory in the directory. Desktop directory.
Cd desktop
Utilize the following instruction to launch the Laravel-Scout program. This will create an Dockerized application, by providing boilerplate code required.
curl -s https://laravel.build/laravel-scout-app | bash
Once the procedure is complete You can then alter your directory by using the command cd laravelscout
. Next, execute your sail-up
command inside the directory of your project to launch with the Docker containers that are running the app.
NOTE: On many Linux distributions, it's possible to execute the following commands with the sudo
command and be granted elevated rights.
./vendor/bin/sail up
You might encounter an error:

To resolve this issue, you can use the app_port
variable to specify the port sail up: sail up
command:
APP_PORT=3001 ./vendor/bin/sail up
After that, you can run this command to start the program using Artisan on the PHP. This is the PHP server.
php artisan serve

From your web browser, navigate to the running application at http://127.0.0.1:8000. The program will open your Laravel welcome page with the URL you are used to.

How can I integrate Laravel Scout into the App
On your terminal, type this command to open the Composer PHP module manager. This will permit Laravel Scout to the project.
composer require laravel/scout
Then, you can publish your Scout configuration file with this command provided from the seller. This will add your scout.php
configuration file to your program's setting directory.
php artisan vendor:publish --provider="Laravel\Scout\ScoutServiceProvider"
Make your boilerplate .env file to include the SCOUT_QUEUE
variable. It is an boolean.
SCOUT_QUEUE SCOUT_QUEUE
value allows Scout to store operations in a queues. This results in faster responses. If this value isn't set, Scout drivers like Meilisearch aren't capable of incorporating new information quickly.
SCOUT_QUEUE=true
DB_HOST=127.0.0.1
How do you mark a model and configure the Index
Scout doesn't enable searchable models of data by default. You must explicitly mark a model as searchable using its Laravel\Scout\Searchable
trait.
The first step is to create the data model in an an illustration Train
program and mark the model as searchable.
How do you create an Model
In order to use the train
application, it's vital to save names, which are placeholders for every train that exists.
Make use of to use to use the Artisan command to make the transfer. You can give it the name the table create_trains.
.
php artisan make:migration create_trains_table

The information is stored within the form of a file. The information is a mixture of your name and the time stamp of the date.
Navigate to the migration file in the database/migrationsdirectory. directory.
To include an extra title column copy, and paste the code in line 17 after () column in line 17. () > column in line 17. The code is added to the title column.
$table->string('title');
To make the change take the steps listed below.
php artisan migrate

When you have completed the database migrations and creating an application file with the name Train.php in the model/app directory.
How To Add the LaravelScoutSearchable Trait
Mark the Train
model for search by adding the Laravel\Scout\Searchable
trait to the model, as shown below.
What is the best way to utilize Algolia together with Scout
If you're looking for your first full-text search using Laravel Scout You'll need the Algolia driver. Algolia is an application as a service (SaaS) system that permits users to search through huge quantities of data. It offers a user-friendly dashboard that developers can access on the internet who manage their search engines as along with an API with robust interfaces that users have access to through an application called the Software Development Kit (SDK) in your programming language their preferred programming language.
In the Laravel program, you'll be able to use it in conjunction with the Algolia client program that is designed specifically for PHP.
How do I configure Algolia
For starters, you'll must download to install the Algolia searching client PHP application to your computer.
Follow the instructions below.
composer require algolia/algoliasearch-client-php
Next, you must make sure you have your Application ID and Secret API Key credentials to Algolia within the .env file.
By using your browser, look around your Algolia dashboard looking for your Application ID and secret API Key credentials.
Click Settings in the lower part of the left-hand sidebar. Then you will go to Settings. settings page.
After that, you can choose to view API Keys under The Access and Team section on the Settings page. You will be able to view the API keys for the account that you created. Algolia account.

On the API Keys page, take note of the App ID as well as the key for Admin API value. These credentials serve to confirm the exchange of information between Laravel application and Algolia.

Include the following code in your .env file by using your editor for code and then replace them with the appropriate Algolia API secrets.
ALGOLIA_APP_ID=APPLICATION_ID ALGOLIA_SECRET=ADMIN_API_KEY
In addition, you could modify your SCOUT_DRIVER
variable by using this application to alter the value to meilisearch
to algolia
. This will inform Scout to utilize algolia instead. Algolia driver.
SCOUT_DRIVER=algolia
How can I create the Application Controllers
Within the app/Http/Controllers/ directory, create a TrainSearchController.php file to store a controller for the application. It will display and update information in the Train
model.
Add the following code block into the TrainSearchController.php file to build the controller.
has('titlesearch')) $trains = Train::search($request->titlesearch) ->paginate(6); else $trains = Train::paginate(6); return view('Train-search',compact('trains')); /** * Get the index name for the model. * * @return string */ public function create(Request $request) $this->validate($request,['title'=>'required']); $trains = Train::create($request->all()); return back();
How can I make an Application Routes
This is the stage where you build the routes that will be listed and add train lines to your database.
Go through in the routes/web.php file and replace the existing code by the block below.
name ('trains-lists'); Route::post('create-item', [TrainSearchController::class, 'create']) -> name ('create-item');
The following code generates two possible routes for the app. The one which is an request for a GET
request made from the trains-lists
route lists all of the details about trains. An POST
request from"/create" "/create"
route is used to create fresh train information.
How to Create an Application Views
Create a file within the resources/views/ directory and name it Train-search.blade.php. The file will display the user interface which lets you search.
Add the content of the code block below into the Train-search.blade.php file to create a single page for the search functionality.
!DOCTYPE HTML> HTML> Laravel - Laravel Scout Algolia Search Examples "container">Laravel Full-Text search using Scout The Scout Autocomplete="off"@if(count($errors)) Whoops! It's a problem when you input your data. @foreach($errors->all() as $error) $error @endforeach @endif $errors->first('title') Create New Train Train Management Search @if($trains->count()) @foreach($trains as $key => $item) @endforeach @else @endif Id Train Title Creation Date Updated Date ++$key $item->title $item->created_at $item->updated_at No train data available $trains->links()
The HTML code in the above image has a form element, which includes an input field as well as the option of entering the name of a train prior to recording it in databases. It also contains an HTML table that displays ID, title, created_at, along with the updated date information on the train's database entry.
What is the best way to use Algolia Search
To view the page, navigate to http://127.0.0.1:8000/trains-lists from your web browser.

The database isn't completely loaded, so you must input the title of the demo train using the input box and after that, click "Create New" Train to save the train.

For a search term to search, type in any keywords from trains you've saved into the input box for the Input Title For Search input box and then hit search.
You can see this in the image below. As you can see in the image below the only entries that contain the phrase "keyword" in the title will show.

Meilisearch in conjunction with Laravel Scout
Developers are able to create and host an account with Meilisearch using their cloud or in-house infrastructure. Meilisearch also offers a free test cloud offering like Algolia to developers that want to use the product without having to manage the infrastructure.
To connect Meilisearch with Laravel it is required to install the Meilisearch. Laravel application, use this command in the terminal for the project.
composer require meilisearch/meilisearch-php
Next, you will need to modify the Meilisearch variables inside the .env file to improve its user-friendliness.
Replacing the SCOUT_DRIVER
, MEILISEARCH_HOST
and MEILISEARCH_KEY
variables of the .env file with those below.
SCOUT_DRIVER=meilisearch MEILISEARCH_HOST=http://127.0.0.1:7700 MEILISEARCH_KEY=LockKey
Its SCOUT_DRIVER
key is the driver that Scout is expected to utilize. MEILISEARCH_HOST
is the name of the web address where the Meilisearch instance you have is. While not necessary for development however, incorporating MEILISEARCH_KEY
when you are in production is highly recommended.
NOTE: Comment out the Algolia ID and Secret when choosing Meilisearch as your preferred driver.
After you've completed the .env configurations, it is time to index the entries you have already created using the Artisan command as follows.
PHP artist Scout: Import "App\Models\Train"
Laravel Scout is equipped with Database Engine
This engine utilizes "where-like" clauses, together with full-text as well as indexes of your database in order to find the best results to your searching. You do not need to be the indexing of your database in order to be able to utilize the engine in your the database.
For the database engine for it to function, change the SCOUT_DRIVER
.env variable to the database.
Open by opening the .env file within the Laravel application. Make changes to the values that are in the SCOUT_DRIVER
variable.
SCOUT_DRIVER = Database
If you change your driver away from the database engine Scout is able to switch into the database engine and do full-text searches.
Collection Engine that integrates Laravel Scout
In addition to the database engine, Scout provides an additional collection engine. The engine uses "where" clauses as well as filters to identify which results are the most relevant for your query.
In contrast to the database engine, the collection engine can be used in conjunction with the vast majority of databases that are relational. Laravel can also assist with.
You can use the engine to collect data by changing the SCOUT_DRIVER
environment variable to the collection
or by manually specifying the driver that collects within the Scout Configuration file.
SCOUT_DRIVER is a collection
Explorer and Elasticsearch
Thanks to the strengths in Elasticsearch query, Explorer is described as a modern Elasticsearch driver, which is compatible together with Laravel Scout. Explorer is an entirely compatible Scout driver, and offers advantages like the capacity to save, browse and analysing massive quantities of information at a time. Elasticsearch is integrated with Laravel gives results within milliseconds.
To use Elasticsearch Explorer, the Elasticsearch Explorer driver that is part of the Laravel program, you'll need to set up your boilerplate docker-compose.yml file that is created by the script Laravel-Scout. You'll then need to set additional settings for Elasticsearch and then re-start the containers.
Browse to your docker-compose.yml file and modify its content using the next.
# For more information: https://laravel.com/docs/sail version: '3' services: laravel.test: build: context: ./vendor/laravel/sail/runtimes/8.1 dockerfile: Dockerfile args: WWWGROUP: '$WWWGROUP' image: sail-8.1/app extra_hosts: - 'host.docker.internal:host-gateway' ports: - '$APP_PORT:-80:80' - '$VITE_PORT:-5173:$VITE_PORT:-5173' environment: WWWUSER: '$WWWUSER' LARAVEL_SAIL: 1 XDEBUG_MODE: '$SAIL_XDEBUG_MODE:-off' XDEBUG_CONFIG: '$SAIL_XDEBUG_CONFIG:-client_host=host.docker.internal' volumes: - '. :/var/www/html' networks: - sail depends_on: - mysql - redis - meilisearch - mailhog - selenium - pgsql - elasticsearch mysql: image: 'mysql/mysql-server:8.0' ports: - '$FORWARD_DB_PORT:-3306:3306' environment: MYSQL_ROOT_PASSWORD: '$DB_PASSWORD' MYSQL_ROOT_HOST: "%" MYSQL_DATABASE: '$DB_DATABASE' MYSQL_USER: '$DB_USERNAME' MYSQL_PASSWORD: '$DB_PASSWORD' MYSQL_ALLOW_EMPTY_PASSWORD: 1 volumes: - 'sail-mysql:/var/lib/mysql' - './vendor/laravel/sail/database/mysql/create-testing-database.sh:/docker-entrypoint-initdb.d/10-create-testing-database.sh' networks: - sail healthcheck: test: ["CMD", "mysqladmin", "ping", "-p$DB_PASSWORD"] retries: 3 timeout: 5s elasticsearch: image: 'elasticsearch:7.13.4' environment: - discovery.type=single-node ports: - '9200:9200' - '9300:9300' volumes: - 'sailelasticsearch:/usr/share/elasticsearch/data' networks: - sail kibana: image: 'kibana:7.13.4' environment: - elasticsearch.hosts=http://elasticsearch:9200 ports: - '5601:5601' networks: - sail depends_on: - elasticsearch redis: image: 'redis:alpine' ports: - '$FORWARD_REDIS_PORT:-6379:6379' volumes: - 'sail-redis:/data' networks: - sail healthcheck: test: ["CMD", "redis-cli", "ping"] retries: 3 timeout: 5s pgsql: image: 'postgres:13' ports: - '$FORWARD_DB_PORT:-5432:5432' environment: PGPASSWORD: '$DB_PASSWORD:-secret' POSTGRES_DB: '$DB_DATABASE' POSTGRES_USER: '$DB_USERNAME' POSTGRES_PASSWORD: '$DB_PASSWORD:-secret' volumes: - 'sailpgsql:/var/lib/postgresql/data' networks: - sail healthcheck: test: ["CMD", "pg_isready", "-q", "-d", "$DB_DATABASE", "-U", "$DB_USERNAME"] retries: 3 timeout: 5s meilisearch: image: 'getmeili/meilisearch:latest' ports: - '$FORWARD_MEILISEARCH_PORT:-7700:7700' volumes: - 'sail-meilisearch:/meili_data' networks: - sail healthcheck: test: ["CMD", "wget", "--no-verbose", "--spider", "http://localhost:7700/health"] retries: 3 timeout: 5s mailhog: image: 'mailhog/mailhog:latest' ports: - '$FORWARD_MAILHOG_PORT:-1025:1025' - '$FORWARD_MAILHOG_DASHBOARD_PORT:-8025:8025' networks: - sail selenium: image: 'selenium/standalone-chrome' extra_hosts: - 'host.docker.internal:host-gateway' volumes: - '/dev/shm:/dev/shm' networks: - sail networks: sail: driver: bridge volumes: sail-mysql: driver: local sail-redis: driver: local sail-meilisearch: driver: local sailpgsql: driver: local sailelasticsearch: driver: local
After that, execute the following command to get the most current Elasticsearch image you've added to docker-compose.yml. docker-compose.yml file.
docker-composes up
Make use of the Composer function below to integrate Explorer in the project.
composer require jeroen-g/explorer
Additionally, you need to create an administrator's profile for this Explorer driver.
Utilize using the Artisan command to create your explorer.config file for the storage of your settings.
php artisan vendor:publish --tag=explorer.config
The configuration file that was created can be found within the directory known as"/config" directory.
Within the config/explorer.php file, you can refer to the model you have created by using indexes key. Indexes
key.
'indexes' => [ \App\Models\Train::class ],
Modify the values in the SCOUT_DRIVER
variable within the .env file to the value of elastic
in order to permit Scout to use in the Explorer driver.
SCOUT_DRIVER = elastic
If you're in this situation, it's your responsibility to incorporate Explorer in your Train
model employing the Explorer interface and then overriding mapspableAs()
method.
Launch with the Train.php file within the App Models directory. Replace your existing code by the code below.
$this->Id, 'title' => $this->title, ];
With the help of the code you included the above code, you'll have access to Explorer to search for the text in the model. Train
model.
Summary
To PHP designers, Laravel and add-ons like Scout make it a breeze to incorporate fast and effective full-text search capabilities. Utilizing Laravel's Database Engine, Collection Engine as well as the features provided by Meilisearch and Elasticsearch that allow you to integrate with the database's information and integrate advanced search capabilities in milliseconds.
It's easy to handle your database and keeping current ensures that your clients get the most enjoyable experience possible while your code stays clean and streamlined.
- Easy setup and administration on My dashboard. My dashboard
- Assistance is available at all times.
- The most powerful Google Cloud Platform hardware and network is powered by Kubernetes for the highest capacity
- The most sophisticated Cloudflare integration that speeds up and increases security
- The coverage of global viewers is boosted with as many as 35 data centers and more than 275 PoPs across the globe
This post was originally posted on here
Article was first seen on here