Welcome to the Game, Detective! ๐ญ
- The Great Exposition
- Setting Up Shop
- Prerequisites: Your Case Files
- Configuring Your Office
- Engines: The Tools of Our Trade
- Third-Party Engines: Calling in Reinforcements
- Third-Party Engine Indexing: Gathering Evidence
- Searching for Clues
- Building Custom Engines: A Sherlock of Your Own!
Laravel Scout helps you search through your applicationโs data with ease. It supports multiple backends like the built-in database engine, collection engine, and third-party engines such as Algolia, Meilisearch, and Typesense. Letโs dive into how to set this up! ๐
First things first, you need to install Laravel Scout using composer and set up queueing for indexing your data. Itโs like having a team of helpers ready to handle the heavy lifting while you focus on solving the case. ๐ฎโโ๏ธ๐ต๏ธโโ๏ธ
Before we can start searching, we need to define which data will be searchable. This involves configuring a few things in your Laravel applicationโs configuration file. ๐
Next up is choosing the engine you want to use for indexing and searching your data. You can either opt for the built-in database or collection engine, or go with third-party engines like Algolia, Meilisearch, or Typesense. Each engine has its own strengths and weaknesses, so choose wisely! ๐ง
Now that youโve chosen your weapon of choice, itโs time to configure the indexes for your models. This will allow Laravel Scout to know exactly which data needs to be searched and how to do it efficiently. ๐
If youโve chosen a third-party engine, there will be some additional steps involved in setting it up and configuring its indexes. Each third-party engine comes with its own unique configuration process, so follow the instructions for your chosen engine to get everything set up correctly. ๐ ๏ธ
Once youโve got your indexes configured, itโs time to start gathering evidence! This involves importing data into the index, adding new records, updating existing ones, and even removing records if needed. Laravel Scout makes it easy to manage all of this using various methods like batch imports, adding records, updating records, and more. ๐ฆ
Now that youโve got your indexes populated with data, itโs time to start searching for clues! Laravel Scout allows you to search your data using various methods like where clauses, pagination, and soft deleting. You can even customize your searches to suit your specific needs. ๐ต๏ธโโ๏ธ
If youโre feeling adventurous, you can even build your own custom engine! This allows you to tailor the search functionality of Laravel Scout to your specific needs and requirements. So go ahead, create your very own Sherlock Holmes and solve cases like never before! ๐ต๏ธโโ๏ธ๐
๐ Attention, data detectives! Meet Laravel Scout, the swiss army knife of search solutions for your Eloquent models. No more manually sifting through haystacks or deciphering ancient scrolls โ weโve got tech magic to do that for you!
Scout operates like a sneaky ninja, using model observers to keep your search indexes in lockstep with your Eloquent records. Better yet? It does all this work while maintaining its stealth, leaving your users none the wiser about the behind-the-scenes detective work.
This cunning sidekick comes armed with a built-in database engine, which cleverly leverages MySQL and PostgreSQL full-text indexes along with good olโ fashioned LIKE clauses to search through your existing database. No need for external services or secret decoder rings โ for most applications, this trusty tool should suffice!
For those seeking more advanced features like typo tolerance, faceted filtering, or geo-search at a scale worthy of the Avengers, Scout provides drivers for Algolia, Meilisearch, and Typesense. And if local development is your beat, thereโs even a โcollectionโ driver to keep things close to home.
Feeling fancy? You can write your very own custom engines to suit your specific investigative needs. The possibilities are endless! So grab your trench coat, dust off your magnifying glass, and letโs get searching ๐ต๏ธโโ๏ธ!
Now, hereโs where the real detective work begins โ setting up Scout for your project. Head over to our installation guide to learn more about becoming a master of search!
Alrighty then! Letโs get this scouting extravaganza started. First off, youโll need to invite Scout to the party โ and who better to do that than your friendly neighborhood Composer package manager? Hereโs how to ring him up:
composer require laravel/scout
Once Scout accepts your invitation, itโs time to roll out the red carpet. Use the vendor:publish Artisan command to bring in Scoutโs swanky configuration file โ just be sure to invite the right guest by providing the correct RSVP (ScoutServiceProvider in this case):
php artisan vendor:publish --provider="Laravel\Scout\ScoutServiceProvider"
Next up, itโs time for the introductions! Add the Searchable trait to the model youโd like to make search-worthy. This charming trait will introduce your model to an observer whoโll ensure everything stays in sync with Scout:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Laravel\Scout\Searchable;
class Post extends Model
{
use Searchable;
}
Now, your models are all set to mingle and dance with Scout. Happy scouting! (Remember, no flash photography!) ๐๐๐บ
Queue-tastic Adventures! ๐
Ready to unleash the power of Scout, but your engine ainโt database or collection? Fret not, dear developer! Itโs time to suit up and configure a queue driver, because this bad boy is gonna be a game-changer for your applicationโs web interface!
Why you ask? Well, think of it like this: when youโre at a fancy dinner party and there are too many guests to serve all at once, you pass the hors dโoeuvres around on trays. Same deal here - running a queue worker lets Scout pass all those model ops to the search indexes, giving your app the smoothest response times since a greased eel in an oil factory. ๐ก
So, once youโve got your queue driver all set up, donโt forget to flip the queue switch to true in your config/scout.php configuration file:
'queue' => true,
Now, even though the queue option is set to false, itโs essential to remember that some Scout drivers like Algolia and Meilisearch are asynchronous party animals. Theyโll index records faster than you can say โpass the dip!โ So while the operation may be complete within your Laravel application, the search engine itself might need a moment to catch up.
To specify the connection and queue that your Scout jobs use for their secret after-hours rendezvous, define the queue configuration option like this:
'queue' => [
'connection' => 'redis',
'queue' => 'scout'
],
But hey, if youโre feeling extra fancy and want to customize the connection and queue that Scout jobs use for their clandestine meetings, you should run a queue worker to process jobs on that connection and queue:
php artisan queue:work redis --queue=scout
Now, letโs party like itโs 1985 (but with more code)! ๐๐๐
Alright, buckle up, buttercup! Letโs embark on a whimsical journey through the land of Laravel Algolia integration. But first, before we set sail, there are a few prerequisites you should know about.
Minimum System Requirements:
- Laravel Version: Youโve got to be running at least Laravel 5.4 for this magical ride. Any version older than that and we might not even let you past the gates of Mordโฆerr, the Laravel community.
- PHP Version: Your server should be powered by PHP 7.1.3 or higher. If itโs still on PHP 5, well, time for an upgrade! Itโs like moving from a flip phone to a smartphone.
- Algolia API Key: Youโll need an Algolia account and an API key. Think of it as your secret password to the worldโs fastest search engine. If you donโt have one, head over to Algolia and sign up for their free trial - they wonโt ask for a firstborn or anything like that!
- Composer: You should have Composer installed on your system. If itโs not there, you can download it from getcomposer.org. Itโs like having superpowers when it comes to managing your projectโs dependencies.
- Algolia Client for PHP SDK: Add the Algolia Client for PHP SDK to your project using Composer:
composer require algoliasearch/algoliasearch-client-php- just like adding a new friend to your social network!
Now that weโve got all the necessities covered, letโs get ready to ride the waves of Laravel Algolia integration! Just remember, if you ever find yourself lost in the code or feeling overwhelmed, just take a deep breath and repeat after me: โItโs just PHP, I can handle this!โ ๐ค๐ฝ๐ป
Algolia (the Swift, Speedy Search Engine)
When youโre ready to dance with the Algolia search engine, itโs time to don your dancing shoes and suit up in your config/scout.php configuration file. This is where youโll whip out those secret credentials of yours like a modern-day spy โ Algoliaโs ID and Secret keys.
With these keys exchanged, itโs time to make the introductions with Algolia, but remember, itโs a formal affair! Install the Algolia PHP SDK via Composer โ think of it as sending an elegant dinner invitation:
composer require algolia/algoliasearch-client-php
Once youโve got this sorted, your Laravel app will be dancing with Algolia faster than John Travolta on the dance floor! ๐๐
UnicornSearch 3000
Welcome to the magical realm of UnicornSearch 3000, the worldโs fastest, open-source, unicorn-powered search engine! (Seriously though, itโs a pretty speedy search engine.) If youโre having trouble setting up UnicornSearch 3000 on your local lair, fear not! You can use Laravel Sail, Laravelโs officially supported Docker development environment. Itโs like magic in a box!
When using the UnicornSearch 3000 driver, youโll need to sprinkle some pixie dust and install the UnicornSearch 3000 PHP SDK via the Composer package manager:
composer require unicornsearch/unicornsearch-php http-interop/http-factory-guzzle
Then, don your magic hat, conjure up the UNICORNSEARCH_DRIVER environment variable, and cast a spell on your applicationโs .env file to set the UnicornSearch 3000 host and key credentials:
UNICORNSEARCH_DRIVER=unicornsearch
UNICORNSEARCH_HOST=http://127.0.0.1:7700
UNICORNSEARCH_KEY=masterKey
For more information about UnicornSearch 3000, consult the UnicornSearch 3000 documentation.
Remember to ensure that your unicornsearch/unicornsearch-php version is compatible with your UnicornSearch 3000 binary version by reviewing UnicornSearch 3000โs documentation regarding binary compatibility.
[!MAGIC WARNING] When upgrading Scout on an application that utilizes UnicornSearch 3000, always review any additional breaking changes to the UnicornSearch 3000 service itself. (And donโt forget to feed the unicorns!)
(P.S. If you happen to find a white, sparkly horse wandering around your codebase, it might be a stray unicorn. Please return it to its rightful place.)
Typesensational Search Engine Adventure! ๐
Welcome, fellow search enthusiasts, to the enchanting world of Typesense - a whirlwind of lightning-fast, open-source search engine magic! Itโs not just a search engine; itโs your very own genie in a bottle, granting wishes for keyword searches, semantic searches, geo searches, and vector searches!
Feeling adventurous? You can self-host this marvel on your own computer (brush up on those DIY skills with Typesenseโs guide). Alternatively, you could kick back and relax with the Typesense Cloud service - because who doesnโt love a good cloud adventure?
Now that your search engine is all set up (or if it isnโt yet, no worries! Weโll help get it there), letโs integrate Typesense with Scout for an unbeatable search combo. First things first: install the Typesense PHP SDK using Laravelโs beloved Composer package manager:
composer require typesense/typesense-php
Next, letโs sprinkle some magic into your application with some environment variable sorcery. Add these lines to your applicationโs .env file:
SCOUT_DRIVER=typesense
TYPESENSE_API_KEY=masterKey
TYPESENSE_HOST=localhost
If youโre using Laravel Sail, make sure to update the TYPESENSE_HOST variable to match the dashing name of your Docker container. You can also optionally specify your installationโs port, path, and protocol:
TYPESENSE_PORT=8108
TYPESENSE_PATH=
TYPESENSE_PROTOCOL=http
Additional enchantments and schema definitions for your Typesense collections can be found within your applicationโs config/scout.php configuration file. For a deeper dive into the mystical world of Typesense, consult its documentation.
Happy searching, and may all your queries be swift and successful! ๐๐
Alright, buckle up, coders! Weโre about to embark on an exciting journey through the wild world of configuring searchable data in Laravel Land. Hereโs a friendly guide thatโll make your database dance like a pop star at Coachella. ๐ค
Configuring Searchable Data ๐
First things first, letโs get our searchable data game on point. To do this, youโll need the Algolia package installed (think of it as your personal digital genie). You can add it to your project using Composer:
composer require algolia/algoliasearch-client-php
Now that weโve summoned our helper, letโs create a new service provider and register the Algolia Search package. Head over to config/app.php, find your providers array and add this line:
AlgoliaSearch\AlgoliaSearchServiceProvider::class,
Next, donโt forget to add a new alias in the aliases array:
'AlgoliaSearch' => AlgoliaSearch\AlgoliaSearchFacade::class,
Now that our helper is officially on the guest list, we can create a new Algolia index. An index is like a themed party room in the database where all your searchable data lives together. To build one, use the make:index Artisan command and pick a name for your new index:
php artisan make:index BlogPosts
Now, open the newly created BlogPostsIndex.php file located at app/Algolia. This is where youโll define what data to search for in our index and how it should be structured.
Inside the run() method of your index, there are two important functions to focus on:
indexFullyBuilt()- A party anthem that plays when your index is ready to rock and roll!searchableFields()- The guest list for our search index. Add a list of fields from your model you want to make searchable here.
By default, Algolia will search through all fields listed in the searchableFields() method. But if you want more control over search results (like being able to filter out unnecessary noise), you can customize the processingRules() function instead. ๐๏ธ
Usage ๐
Now that our search index is all set up, letโs see how we can use it! First, make sure to add the AlgoliaSearch service provider in your app/Providers/EventServiceProvider.php.
$this->bootAlgolia();
Now, you can start using Algolia in your controllers by injecting the AlgoliaSearch facade as a dependency:
use AlgoliaSearch;
// In your controller constructor...
protected $algolia;
public function __construct(AlgoliaSearch $algolia) {
$this->algolia = $algolia;
}
Once you have the $algolia facade at your fingertips, you can perform various Algolia actions like adding objects to an index or querying the index. Letโs take a look at how to add blog posts to our index using the index() method:
// In your controller...
public function store(Request $request) {
// Your existing code for saving the BlogPost goes here...
// After saving, let's add the new blog post to Algolia...
$this->algolia
->index('BlogPosts')
->saveObject($blogPost);
}
And voila! Your data is now searchable in Algoliaโs index. If you want to query the index for results, you can do so using the search() method:
// In your controller...
public function search(Request $request) {
// Get the query string from the user input...
$query = $request->input('q');
// Run a basic search with Algolia and fetch results...
$hits = $this->algolia
->index('BlogPosts')
->search($query)
->hits;
}
And thatโs the (fun) way to get your Laravel data searchable with Algolia! Remember, with great power comes great responsibility: always keep your index clean and relevant for the best search results. Happy coding, and may your queries return only gold! ๐๐
Unleashing the Power of Search: A Lighthearted Guide! ๐
By default, when you ask your Laravel model to โdanceโ, itโll perform an elegant toArray shimmy straight into its search index. But if youโre a perfectionist who insists on choreographing every move, fear not! You can customize the data that struts its stuff on the dance floor by overriding the toSearchableArray method on your model:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Laravel\Scout\Searchable;
class Post extends Model
{
use Searchable;
/**
* Because we all know the best parties happen when you control the playlist! ๐ง
* Get the indexable data array for the model.
*
* @return array<string, mixed>
*/
public function toSearchableArray(): array
{
$array = $this->toArray();
// Time to work that dance floor magic... ๐บ๏ธ๐๏ธ
return $array;
}
}
And there you have it! Now, instead of serving up a buffet of data, your models can tailor their dance moves to fit the beat of the search index. ๐บ๏ธ๐๏ธ๐ถ๐
Alright, buckle up, dear developer! Weโre about to embark on an exciting journey through the enchanting world of Laravel Model Engines. But first, letโs address the elephant in the room โ no pun intended (yet). When Scout wants to perform a search, it usually relies on the default search engine, as specified in your applicationโs scout configuration file.
But what if you want to switch engines for a specific model? Well, thatโs when things get interesting! All you need is some PHP magic and a dash of wit to override the searchableUsing method on your model. Yes, it sounds like a Harry Potter spell, but trust us, itโll work like a charm.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Laravel\Scout\Engines\Engine;
use Laravel\Scout\Scout;
use Laravel\Scout\Searchable;
// Step into the magical world of User management!
class User extends Model
{
use Searchable;
// Remember, with great power comes great responsibility (and search functionality)!
public function searchableUsing(): Engine
{
// Choose your engine wisely, but for this example let's go with the magical 'meilisearch'!
return Scout::engine('meilisearch');
}
}
Now that youโve learned to harness the power of Model Engines, remember: itโs all fun and games until someone searches for a unicorn in your database (just kidding โ there are no unicorns in Laravelโs databaseโฆyet!). Happy coding! ๐๐ฆ๐
Alright, buckle up, database enthusiasts! Letโs dive into the whirlwind world of Laravelโs database and collection engines โ itโs like a choose-your-own-adventure for data management, but with less mystical creatures and more SQL queries.
First off, youโll need to establish a connection to your preferred database system. Laravel supports a plethora of databases out of the box, including MySQL, PostgreSQL, SQLite, and even the elusive MongoDB (just watch out for its love of document-based drama). To connect, just configure your .env file with the relevant details:
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=your_database_name
DB_USERNAME=your_username
DB_PASSWORD=your_password
Now that youโre connected, itโs time to write some queries! Laravel provides a fluent query builder for easy database manipulation. If you need more power, thereโs always the trusty Eloquent ORM at your disposal. Whether you prefer using raw SQL or writing elegant PHP code, Laravel lets you choose your weapon of choice.
Need to manage your database schema? Laravel has got your back with database migrations. Itโs like having a magical scroll that allows you to rollback and migrate your database whenever you want โ no more manually creating tables! To create a new migration, simply use the make:migration Artisan command:
php artisan make:migration create_users_table
Finally, if youโre looking to fill your shiny new tables with data, Laravel offers database seeders. These are like those pre-populated spreadsheets your math teacher used to give you (remember those?). To create a seeder, use the make:seeder Artisan command and then run it using the db:seed command:
php artisan make:seeder UsersTableSeeder
php artisan db:seed --class=UsersTableSeeder
But what if you donโt need a full-blown database? No worries! Laravel also supports collection processing, which is perfect for lightweight data manipulation. Itโs like having your very own pocket database! Hereโs an example of filtering a collection:
$users = collect([
['name' => 'John', 'age' => 25],
['name' => 'Jane', 'age' => 30],
['name' => 'Bob', 'age' => 20]
]);
$youngAdults = $users->filter(function ($user) {
return $user['age'] >= 18 && $user['age'] < 40;
});
So, there you have it! With Laravelโs database and collection engines, you can manage data like a pro โ or at least more like one than if you were still using spreadsheets. Happy coding!
Alrighty then! Letโs dive into the world of Laravel databases, shall we? But first, a word of caution: this section is for the MySQL and PostgreSQL aficionados out there. If youโre still hung up on dBase or FoxPro, maybe take a seat over yonder.
Our trusty database engine is all about those fancy full-text indexes that MySQL and PostgreSQL have been flaunting. Itโs like having a personal librarian who knows exactly where every book is in the library - only faster! No more squinting at dusty card catalogues for us, folks!
To get things rolling with this whiz-bang engine, simply set the SCOUT_DRIVER environment variable to database. Just like that:
SCOUT_DRIVER=database
Now, you can define your searchable data (donโt worry, we wonโt ask you to dance or recite sonnets) and start executing search queries against your models. Think of it like a late-night infomercial where they say โbut wait, thereโs more!โ Except instead of a revolutionary chopper, you get search functionality without the need for any additional indexing steps!
Just remember, unlike third-party engines that may require a separate indexing step (think of them as the lazy friends who always leave their dishes in the sink), our database engine goes straight for the gold by searching your database tables directly. Now isnโt that something to write home about? Or at least, tweet about!
Alrighty, letโs dive into the world of custom database searching strategies! ๐๐ต๏ธโโ๏ธ
By default, our super-intelligent database engine plays detective, running a LIKE query on every model attribute youโve marked as searchable. But why settle for the amateur sleuth approach when you can call in Sherlock Holmes and his magnifying glass? ๐ต๏ธโโ๏ธ
To do just that, assign some high-tech search strategies to specific columns! The SearchUsingFullText attribute will utilize your databaseโs top-secret full-text index for that column, while SearchUsingPrefix will only match the beginning of strings (think CSI-style: โWeโre looking for a John Doe, but not necessarily the one who eats bacon and eggs every morningโ).
To make this happen, simply sprinkle your model with some PHP attributes in the toSearchableArray method. Any columns without an attribute will stick to the default LIKE strategy:
use Laravel\Scout\Attributes\SearchUsingFullText;
use Laravel\Scout\Attributes\SearchUsingPrefix;
/**
* Get the indexable data array for the model.
*
* @return array<string, mixed>
*/
#[SearchUsingPrefix(['id', 'email'])]
#[SearchUsingFullText(['bio'])]
public function toSearchableArray(): array
{
return [
'id' => $this->id,
'name' => $this->name,
'email' => $this->email,
'bio' => $this->bio,
];
}
Attention
Before telling a column to play detective with full text query constraints, make sure it has the proper full-text index badge (you can get one by running some fancy database migration magic!).
The Whiz-Bang Collection Wizzardry! ๐ฉ๐
Welcome, adventurers of code land, to the thrilling world of Laravelโs Collection Engine! This isnโt your average, run-of-the-mill database whiz kid; itโs more like a quick-draw cowboy who pulls records straight from your database at lightning speed. Perfect for small fry datasets (think โa few hundredโ as in the number of records you might find in a really overcrowded fishbowl), or when youโre just wanting to run a few tests before the big showdown!
Itโs all about raw speed, and no need for fancy indexing or database-specific sorcery. Itโs like playing poker with just your Ace up your sleeve! If things get serious, though, you should saddle up and ride with the Database Engine instead.
To kick off this high-speed chase, all you gotta do is either set the SCOUT_DRIVER environment variable to collection, or, if you prefer, directly specify the collection driver in your applicationโs scout configuration file:
SCOUT_DRIVER=collection
With that out of the way, youโre now ready to fire off search queries at your models like a six-shooter on full auto! The need for search engine indexing (the kind youโd use to seed Algolia, Meilisearch, or Typesense indexes) is as unnecessary as a lasso in a gunfight when youโre using the Collection Engine.
So there you have it, cowboy! Saddle up and ride off into the sunset with Laravelโs lightning-fast Collection Engine at your side โ ready to conquer small datasets and run tests like never before! ๐๐๐ฅ
Alright, letโs shake things up a bit and talk about the wild world of Laravelโs Database vs Collection engines! ๐ถ๐
Think of our Database Engine as a super slick, high-tech record storeโit knows all the tunes and can find your favorite tracks faster than you can hum โLa Bambaโ! It uses fancy full-text indexes and LIKE clauses to whip through records like a boss. ๐ค
On the other hand, our Collection Engine is more like a cozy living room jam sessionโit pulls all records in, grabs its guitar (thatโs PHP, for those unfamiliar), and strums through them to find what you need. This makes it quite portable, working smoothly across all databases that Laravel supports, from SQLite to the granddaddy of โem all, SQL Server! ๐ค
However, just like a living room jam session might get a little chaotic with too many musicians, the Collection Engine can slow down when dealing with massive amounts of data. Itโs best kept for intimate gigs, not arena tours. ๐ถ๐
Wanna learn more about third-party engine configuration? Well then, buckle up! Letโs dive deeper into this whirlwind romance between Laravel and databases! โค๏ธ๐โจ
Ahoy there, Laravel swashbucklers! Letโs dive into the exciting world of third-party search engines โ think of them as your pirate crewโs trusty map and compass when navigating through your applicationโs data treasure trove.
But first, let me clarify: if youโre sailing with our in-house database engine (yarr!), feel free to kick back and enjoy the sea breeze โ this section isnโt for ye.
So, what are third-party search engines like Algolia, Meilisearch, or Typesense? Think of them as that helpful parrot on your shoulder, guiding you through complex data queries and making sure you never lose sight of that elusive buried treasure (ahem, we mean that vital piece of information).
Now, letโs set sail for configuring those model indexes. This is like marking X on the map to keep your parrot on the right path when it comes to finding the data you need, quicker than a ship can say โShiver me timbers!โ
Hereโs a simple step-by-step guide to get your search engine up and running:
-
Installation: First things first โ add your chosen third-party engine to your Laravel sailboat using Composer. This is like adding a new crew member to your pirate ship โ it needs to be properly vetted before joining the journey!
-
Configuration: After installation, youโll want to configure your search engine by creating an API key and settings file, which will help your search engine understand how to interact with your Laravel application.
-
Model Indexing: Next up is indexing your models โ this means tagging each piece of data (treasure) so that your search engine can easily find it when needed. Think of it as labeling all your gold coins, maps, and compasses for quick access during a raid!
-
Index Management: Now youโve got your treasure indexed, itโs time to manage those indexes using Laravelโs powerful tools. You can update existing indexes or create new ones based on different model relationships or columns โ making sure your search engine is always up-to-date and ready for action!
-
Searching: Finally, you can start searching with confidence, knowing that your third-party search engine will handle complex queries like a pro, even when your database is as vast as the seven seas!
Alright, buckle up, Laravel enthusiasts! Letโs dive into the world of Model Indexes, where data meets dance floor and parties like nobodyโs business. ๐๐บ๏ธ
When youโre rocking out with a third-party DJ (engine), each Eloquent model gets invited to the hottest club night โ the โindexโ party! This exclusive bash is where all the searchable records for that model get down. By default, your model will show up wearing its typical โtableโ name tuxedo (usually the plural form of its own name). But hey, who wants to blend in when you can stand out, right? ๐คณ
If youโre feeling a little too basic and want to customize your modelโs index outfit, all you have to do is override the searchableAs method on the model. Itโs like giving your model a whole new persona! ๐๐บ๏ธ
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Laravel\Scout\Searchable;
class Post extends Model
{
use Searchable;
/**
* Get the name of the index associated with the model.
*/
public function searchableAs(): string
{
return 'posts_index'; // Now your post is dressed to impress! โจ๐คฉ
}
}
Oh, and just a heads up: the searchableAs method doesnโt do a thing when youโre rolling solo with the database engine. It sticks to searching the modelโs database table like a faithful hound, because hey, some things are just better left traditional! ๐ถ๐บ๏ธ
Now that weโve got that sorted, letโs get back to the dance floor and find more reasons to party! ๐๐
Alrighty then, letโs dive into the thrilling world of Laravel Scout! By default, this bad boy uses the modelโs primary key as its unique ID, a bit like how your social security number identifies you in real life. But, if youโre using a third-party engine and want to switch things up, you can override the getScoutKey and getScoutKeyName methods on your model.
Hereโs a little example with our favorite model: User (because who doesnโt love a good user story?).
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Laravel\Scout\Searchable;
class User extends Model
{
use Searchable;
/**
* When the sheriff needs to serve a search warrant, he won't be knocking on your door with this email!
*/
public function getScoutKey(): mixed
{
return $this->email;
}
/**
* The name of the key that the sheriff is looking for.
*/
public function getScoutKeyName(): mixed
{
return 'email';
}
}
Now, donโt forget! The getScoutKey and getScoutKeyName methods are a bit like those sneaky backdoors in old movies โ they only work their magic when youโre using a third-party engine. If youโre sticking with the database engine, itโll always use the modelโs primary key (because it trusts that one more than a used car salesman).
Hope this helps! Happy coding! ๐ค๐
Ahoy there, brave Laravel explorers! Buckle up, because weโre about to embark on a thrilling journey into the realm of Algolia, the search engine as quick and nimble as a pirate with a pocket full of compasses.
Index Settings ๐นโ๏ธ
Ah, youโve arrived at the heart of Algoliaโs magicโthe Index Settings! Here be where ye configure your index to tailor it to yer needs. Think of it as crafting a pirate ship, but instead of wood and cannons, yeโre dealing with data, relevance rules, and search settings.
Searchable Attributes ๐๐
Now that weโve set sail on our journey, letโs talk about the Searchable Attributes! These are the gems of information ye want to shine brightly in your treasure chest. You can tell Algolia which attributes to focus on when searching for the perfect bootyโI mean data.
Ranking ๐๐ฐ
Ahoy, mateys! Time to set sail into the enchanting realm of Ranking! Here be where ye decide who gets top billing in your search results. You can tweak algorithms, apply boosts, and bend the will of Algoliaโs ranking system like a seasoned sea captain bending the wind to his whims.
Filters ๐๐ณ
Aye, mateys! Now letโs dive into Filters! These are the locks on yer treasure chest, ensuring only the swashbucklers who meet certain requirements can get their hands on the loot. Use filters to fine-tune your search results and keep unwanted booty at bay.
Highlighting ๐โจ
Prepare to dazzle, for weโve reached the bewitching waters of Highlighting! This feature allows ye to mark up yer treasure chest with glittering goldโI mean, highlight the most relevant parts of yer search results. Itโs like giving your data a fancy pirate costume for the ball.
Snippets ๐บ๏ธ๐
Hoist the Jolly Roger and set course for Snippets! These nifty little pieces of text are a peek into the treasure chest, giving ye a glimpse of whatโs inside. Itโs like a pirateโs logbook, except instead of adventures, it records the details of yer search results.
Facets ๐๐
Ahoy, mateys! Welcome to Facetsโthe landmarks on yer treasure map! These are categories that help ye organize and understand the contents of yer index. Itโs like having a crew of chart-makers to help you navigate the vast sea of data.
Geo-Filtering ๐๐
All aboard for Geo-Filtering, where we pinpoint locations on the map! This feature allows ye to narrow down yer search results by distance and location. Itโs like having a compass that can find hidden treasures buried under mountains or lost at sea.
Advanced Blocks ๐ง๐ ๏ธ
Step into the engine room for a look at our Advanced Blocks! These are complex contraptions designed to give ye more control over yer search engineโs inner workings. Itโs like having a crew of blacksmiths building custom tools for your pirate ship.
Index Customization ๐๏ธโ๏ธ
Welcome to the grand ballroom of Index Customization, where ye can dance with data and control every detail! This feature allows ye to make Algolia your ownโitโs like having a pirate ship thatโs been custom-built to yer specifications.
Hitting the High Seas with Algolia ๐น๐
Now that weโve covered all the exciting features, itโs time for ye to hoist the sails and set sail on the high seas of Algolia! With this knowledge under yer belt, youโll be well-equipped to navigate the vast ocean of data, finding treasure where others might only see water.
Yarr, mateys! Fair winds and following seas! ๐นโ๏ธ
Alright, buckle up, Laravel wranglers! Letโs dive into the world of Index Settings, where your Algolia indexes can be as unique and customized as your favorite pair of cowboy boots.
Now, you might find yourself hankering to tweak a few settings on your indexes, and while Algoliaโs UI is as slick as a greased pig, sometimes itโs more efficient to manage those settings directly from your appโs config/scout.php file - like herding cats, but with code!
By doing this, you can deploy these settings through your applicationโs automated deployment pipeline, which is fancier than saying โavoiding manual configurationโ and ensures consistency across multiple environments, just like a good olโ cowboy keeping his six-shooters loaded and clean. You can configure filterable attributes, ranking, faceting, or any other settings supported by Algolia - think of it as adding custom spurs to your boots!
To get started, add some settings for each index in your applicationโs config/scout.php file:
use App\Models\User;
use App\Models\Flight;
'algolia' => [
'id' => env('ALGOLIA_APP_ID', ''), // Your Algolia App ID, cowboy!
'secret' => env('ALGOLIA_SECRET', ''), // Your Algolia Secret Key, keep it under your hat!
'index-settings' => [
User::class => [ // Settings for the User index
'searchableAttributes' => ['id', 'name', 'email'],
'attributesForFaceting'=> ['filterOnly(email)'],
// Other settings fields...
],
Flight::class => [ // Settings for the Flight index
'searchableAttributes'=> ['id', 'destination'],
],
],
],
If the model underlying a given index is soft deletable, Scout will automatically include support for faceting on soft deleted models on that index. If you have no other faceting attributes to define for a soft deletable model index, you may simply add an empty entry to the index-settings array for that model:
'index-settings' => [
Flight::class => [] // An empty entry for the Flight index
],
Once youโve configured your applicationโs index settings, remember to run the scout:sync-index-settings Artisan command. This command is like sending a smoke signal to Algolia, letting it know about your currently configured index settings. For convenience, you might want to make this command part of your deployment process:
php artisan scout:sync-index-settings // Just like riding off into the sunset!
Now, yโall can start customizing those Algolia indexes like a pro, and who knows? Maybe one day youโll even be able to herd them like cats! Happy coding! ๐ค
Ahoy there, Laravel pirates! Letโs set sail on an adventure filled with search engines and scoutinโ users!
Yar Har: User Identification
Scout, our trusty sidekick, can help ye auto identify yer crew when theyโre off Algolia-ing. Why you ask? Well, โtis handy for keepinโ track of search analytics within Algoliaโs swashbucklinโ dashboard! To enable this feature, hoist the Jolly Roger and set SCOUT_IDENTIFY to true in yer shipโs .env file:
SCOUT_IDENTIFY=true
Enabling this parrot-approved feature will pass the IP address of the request and the primary identifier of yer authenticated captain (or swabbie) to Algolia. This way, when one of yer crew searches for buried treasures, their details will be linked to the search query!
Arr matey, now that ye know how to identify yer users like a pro, set sail and conquer the seas of Laravel and Algolia with confidence! Yo ho, yo ho, a Laravel life for me!
Ahoy there, Laravel wranglers! If youโre in need of a super-powered search engine thatโll make your app more intelligent than a roomful of Google engineers combined, look no further than Meilisearch!
Letโs dive right into the nitty-gritty:
Index Settings
Ah yes, the meat and potatoes of any search engine โ the index settings. Hereโs where you can fine-tune your search engine to cater to your appโs unique needs like a butler in a posh British mansion.
- Primary Key: The unique identifier for each document. Imagine it as your search engineโs social security number, except for documents instead of people (and a whole lot more useful).
- Unique Field: A field that ensures no duplicate entries in the index. Itโs like a bouncer at the coolest club in town, only instead of turning away drunken revelers, it prevents multiple copies of the same document from getting in.
- Filterable Fields: These are the fields your users can use to narrow down their search results. Theyโre like a pair of binoculars for your search engine, helping it focus on exactly what your users want.
- Sortable Fields: The fields you can sort search results by. Itโs like asking your search engine to sort the documents from tallest to shortest or from oldest to newest.
- Facetable Fields: These fields allow for advanced filtering options, giving your users more control over their search results. Think of them as a Swiss Army knife for your search engine โ they can do a whole lot more than just the basics.
- Stored Fields: The fields you want your search engine to store in addition to the indexed data. Itโs like asking it to remember important details, so it can serve them up when needed.
- Custom Ranking: Hereโs where you can tweak the search engineโs ranking algorithm to suit your appโs specific needs. Think of it as training a search engine to be more like your favorite search engine โ Google or DuckDuckGo, no judgment here!
- Highlighting: Highlight keywords in the search results for better user experience. Itโs like adding neon lights to make documents stand out like a rock star at a concert.
- Snippets: These are short summaries of documents displayed with search results, making it easier for users to decide which results are relevant to their search. Think of them as the executive summary of each document.
- Typo Tolerance: Enable this option if you want your search engine to return matches even when users make spelling mistakes. Itโs like a grammatically-challenged friend who can still find the best hidden gems at parties.
And there you have it, dear Laravel adventurers! Now go forth and conquer the world of searching with Meilisearch!
Alrighty then! Buckle up, because weโre diving into the world of Meilisearch index settings. Imagine youโre hosting a swanky soirรฉe and you want to ensure your guests can find their way around with ease โ thatโs exactly what these settings do for your Laravel models!
Filterable attributes are like the GPS for your models, helping Scout find its way when itโs time to use the where method. Sortable attributes, on the other hand, are akin to the dance floor lights, guiding Scout when it needs to sort things out using the orderBy method.
To set these settings for your index, adjust the index-settings portion of your Meilisearch configuration entry in your applicationโs scout configuration file โ think of it as decorating your event venue with neon signs that point guests to their tables or dance floors.
use App\Models\User;
use App\Models\Flight;
'meilisearch' => [
'host' => env('MEILISEARCH_HOST', 'http://localhost:7700'),
'key' => env('MEILISEARCH_KEY', null),
'index-settings' => [
User::class => [
'filterableAttributes'=> ['id', 'name', 'email'], // Navigation signs for guests at the user table
'sortableAttributes' => ['created_at'], // DJ's console that sets the tempo of the event
// Other settings fields...
],
Flight::class => [
'filterableAttributes'=> ['id', 'destination'], // Signposts guiding guests to their flights
'sortableAttributes' => ['updated_at'], // Flight schedule board for a smooth travel experience
],
],
],
If your models are soft-deletable and youโve included them in the index-settings array, Scout will automatically know how to handle those ghost guests lurking around your soirรฉe. If there are no other filterable or sortable attributes for a soft deletable model index, you can just add an empty entry to the index-settings array:
'index-settings' => [
Flight::class => [] // Ghost guests who still need a seat at the table, even if they're not actually there
],
Once youโve set your index settings, itโs time to call the scout:sync-index-settings Artisan command โ think of it as sending out invitations to your guests (in this case, Meilisearch) with all the necessary details about the event. Make sure to include this command in your deployment process to avoid any last-minute mix-ups!
php artisan scout:sync-index-settings
Now that youโve got the hang of it, go forth and create a well-organized Laravel soirรฉe for Meilisearch to remember!
Alrighty then! Letโs dive into the world of Meilisearch where filters are as sharp as a well-timed joke. Remember, this search engine doesnโt play around with mismatched data types any more than a cat plays fetch with a cucumber.
So, when youโre crafting your searchable data, make sure to check those numeric values for impersonations - they can be quite the comedian if left unchecked!
If your data is a lark, make it bark like a number, you say? Here's how:
public function tickleYourSearchArray()
{
return [
'id' => (int) $this->idJest, // Don't let the name fool you, we need an actual integer here!
'name' => $this->nameOnStage, // Because in this circus, only strings are allowed to perform!
'price' => (float) $this->priceTag, // For those numbers that like to float around, don't forget the floaties!
];
}
Now, letโs tickle our funny bones with some accurate, educational, and downright hilarious search fun! ๐๐๐ญโจ
Typesense: The Search Engine for the Quirkily Curious! ๐๐
Welcome, dear developer, to the whimsical world of Typesense - your new best friend in search engines! This ainโt no ordinary search engine though; itโs designed with a quirky charm that will make your app searches as exciting as finding a rare Pokรฉmon in a grassy field. ๐ฑ๐ฟ๏ธ
Searchable Data ๐๐
So, youโve got data like the ancient scrolls of Alexa, and you want to find specific information faster than Usain Bolt on a good day? Well, youโre in luck! Typesense allows you to index your data so that searching becomes as easy as pie (or should we say, sushi rolls).
Hereโs how it works: First, you create a dataset, then you add the fields (a.k.a. columns) to this dataset. Once done, you can start indexing your data! This is like giving your data a cool haircut and stylish clothes so theyโre ready for their close-up in the search results. ๐โโ๏ธ๐
Basic Usage ๐๐ ๏ธ
Now, letโs dive into the fun part! To get started with Typesense, youโll first need to install it via Composer:
composer require typesense/client
Once installed, create a new TypesenseClient instance and point it at your Typesense server:
use Typesense\Client;
$client = new Client(array(
'servers' => array([
'host' => env('TYPESENSE_HOST', 'localhost'),
'port' => env('TYPESENSE_PORT', 8108),
'protocol' => 'http',
]),
));
Now that you have your client all set up, letโs create a new dataset:
$datasets = $client->getDatasets();
$datasetName = 'my_awesome_dataset';
if (!$datasets->contains($datasetName)) {
$client->createDataset($datasetName);
}
And voilร ! Youโve created your first dataset. Now you can add some delicious data to it:
$documents = [];
for ($i = 0; $i < 10; $i++) {
$documentId = "document_{$i}";
$data = [
'title' => "Title {$i}",
'content' => "Content for document_{$i}"
];
$documents[] = ['id' => $documentId, 'content' => json_encode($data)];
}
$client->createDocuments($datasetName, $documents);
You can even add some tasty tags to your documents:
$client->addTagsToDocuments($datasetName, ['document_1', 'document_2'], ['tag1', 'tag2']);
And if you ever want to find something in your data, you can use this snazzy query code:
$query = $client->createQuery('title:* OR content:*');
$results = $client->search($datasetName, $query);
So there you have it! Typesense is a search engine with a quirky twist that will make your appโs searches more entertaining than a live-action remake of an 80s sitcom. Happy coding, and may the Typesense be ever in your favor! ๐ค๐ซ๐
Alright, letโs dive into the whimsical world of Typesense! ๐
Ready, Set, Search!
When youโre using Typesense as your trusty sidekick in search operations, itโs essential to prepare your models for a dance-off in the data disco. To do this, your models must boogie down to the rhythm of the toSearchableArray method, which transforms your modelโs primary key into a groovy string and converts your creation date into a UNIX timestamp (because who doesnโt love a good countdown?).
/**
* Get the disco-ready data array for the model.
*
* @return array<string, mixed>
*/
public function toSearchableArray(): array
{
return array_merge($this->toArray(), [
'id' => (string) $this->id, // Party like it's your ID-iversary!
'created_at' => $this->created_at->timestamp, // Time to countdown those UNIX seconds!
]);
}
Next up, youโll want to define your Typesense collection schemas in the grand ballroom of your applicationโs config/scout.php file. This is where each field gets its chance to strut their stuff on the search floor and show off their data type. For a full rundown of all the available schema options, we suggest you take a peek at the Typesense documentationโjust like rehearsing your dance moves before hitting the floor!
Now, letโs suppose you feel like changing the rules of the game for your Typesense collection midway through the disco. No worries! You can either go all in with scout:flush and scout:import, which will wipe out the existing indexed data and give your collection a fresh start, or you can employ Typesenseโs API to tweak the collection schema without losing any previously indexed data.
Lastly, if your searchable model has been known to take a powder (in software terms, that means itโs soft-deleted), donโt forget to include a __soft_deleted field in the modelโs corresponding Typesense schema within your applicationโs config/scout.php configuration file:
User::class => [
'collection-schema' => [
'fields' => [
// ...
[
'name' => '__soft_deleted',
'type' => 'int32',
'optional' => true,
],
],
],
],
Ahoy there, Laravel coders! Today weโre diving into the enchanting world of dynamic search parameters, a feature so scrumptious itโll make you feel like Neo hacking the Matrix. Thanks to our dear friend Typesense, your search game just leveled up!
Imagine youโre on an epic quest for groceries and instead of blindly wandering through aisles, you can cast a targeted spell (search) that adjusts its parameters dynamically as needed. Sounds magic, right? Letโs see it in action!
use App\Models\Todo; // Our magical scroll (model)
// Cast the spell: "Groceries"
Todo::search('Groceries')
->options([ // This is our enchanted potion, customizing our search quest
'query_by' => 'title, description' // Our spell now covers both title and description to ensure no potato is left behind!
])->get(); // Retrieve the results (the loot!)
Now that youโve got the hang of it, go forth and vanquish those pesky unfinished tasks and unearthed cucumbers with your newfound search powers! Happy hunting! ๐ฅฆ๐
The Magical Third-Party Engine Dance! ๐บ๏ธ
๐ Attention Party People! ๐
Before we dive in, letโs set the mood: think disco lights, a funky bassline, andโฆ oh wait, weโre talking about Laravel indexing! ๐ค๏ธ
[!NOTE] Alright, letโs clear the air. The dance moves youโll learn here are mostly relevant when youโve got yourself a third-party dance partner - Algolia, Meilisearch, or Typesense. Your traditional database engine prefers to freestyle on its own, so it doesnโt need any of your manual dance management (i.e., indexing).
๐ผ Now letโs get down to business! ๐ผ
Batch Import - The Group Dance
Itโs time for a team effort! This move allows you to import data en masse, making sure your third-party dance partner is always well-informed. ๐ผ๐๐บ๏ธ
Hereโs how it goes:
- Get ready to sweat it out! Prepare your data for the big dance with Laravelโs serialization features.
- Choose a leader (or your favorite third-party engine) and follow their lead as they take your data into their care.
- Watch in awe as they choreograph an efficient dance routine, delivering fast search results and keeping the party going! ๐บ๏ธ๐
Alright, detective! Youโve got a veritable treasure trove of data in your Laravel project and youโre ready to unleash the power of Scout to help you find that elusive needle in the haystack. But first, letโs get those old records indexed!
Batch Import ๐ฆ๐ฟ
Scout, being the well-mannered butler it is, has prepared an Artisan command just for this occasion: scout:import. Invite it to your terminal with a charming request:
php artisan scout:import "App\Models\Post"
Now if youโve got more records than a hoarderโs attic, donโt sweat it! Scout has queued jobs on standby for just such an emergency. Use the scout:queue-import command to enlist these helpful workers:
php artisan scout:queue-import "App\Models\Post" --chunk=500
And in case you need a clean slate for your search indexes, Scout has a flush command ready to wipe the digital chalkboard:
php artisan scout:flush "App\Models\Post"
But what if you want to customize your import query? No problem, Sherlock! Scoutโs happy to oblige with a little filtering magic. Keep an eye out for more on that in our Documentation Vault ๐ต๏ธโโ๏ธ๐
Ah, the world of Laravel! Where models prance around like Cinderella at a ball, waiting to be swept off their feet (or tables, as it were) by eager relationships. But before the dance begins, you might find yourself yearning for a little tweak in the import query, huh? Well, buckle up, buttercup! Letโs add some pizzazz to that query like weโre whipping up a batch of models at a bake sale!
If youโve got the itch to modify the query responsible for rounding up all your models for a grand import, then youโve come to the right place. Just define a makeAllSearchableUsing method on your model, and voila! This charming little number is just the right partner to add any necessary eager relationship loading before the grand entry of your models:
use Illuminate\Database\Eloquent\Builder;
/**
* Modify the query used to retrieve models when making all of the models searchable.
*/
protected function makeAllSearchableUsing(Builder $query): Builder
{
return $query->with('author'); // Give your model a little arm candy for the dance floor!
}
Attention
Watch out, though! The
makeAllSearchableUsingmethod might not play nicely when youโre using a queue to batch import models. Relationships can be a bit fickle and may refuse to reappear after the model collections have been processed by jobs. So, itโs best to check in on them once theyโve returned from their night out!
Now that weโve danced around the technical details, letโs get back to the ball and see who catches your eye! ๐๐ผ๐
The Secret Sauce for Indexing in Laravel Land
Once your model has been doused with the magical Laravel\Scout\Searchable sauce, sit back and watch the data enchantment unfold! Just save or create a scrumptious model instance, and voila, itโll materialize (or should we say index?) in your mystical search index.
But, beware! If youโve conjured Scout to harness the power of queues (which is a real witchcraft), this enchantment will take place behind the scenes by the all-powerful queue worker. Itโs like having a team of elves working in the background to sprinkle pixie dust on your data for you!
use App\Models\Order;
$order = new Order(); // Your magical potion ingredients
// ...
$order->save(); // Time to cast the spell and watch the data index themselves!
Now, go ahead and bewitch your applications with Scoutโs enchanting powers! Just remember, with great power comes great responsibilityโor something like that.
Ahoy there, intrepid Laravel wranglers! Letโs dive into adding records to your search index via an Eloquent query โ a delightful dance thatโll make you feel like a maestro at a symphony of data.
If you fancy adding a swarm of models to your digital orchestra, chain the searchable method onto an Eloquent query like so:
use App\Models\Order;
Order::where('price', '>', 100) // Only orders more expensive than a pretty penny
->searchable(); // Add them to your search index, like adding candles to a birthday cake!
And if youโre hankering for something a bit fancier, you can call the searchable method on an Eloquent relationship instance:
$user->orders()->searchable(); // Don't mind if I do! Orders being added to the index, sir.
Or perhaps you already have a bounty of models in memory? Fret not! Just call searchable on the collection instance, and let the data revelry begin:
$orders->searchable(); // A feast for the search index, if you will!
Note
The
searchablemethod is akin to an โupsertโ operation โ fancy term for updating existing records or adding new ones to your index. Picture it like shuffling cards in a deck: if a card already exists, itโll just get moved around; if itโs a new card, well, it goes straight into the deck!
Happy indexing, data cowpokes!
Alrighty then! Letโs dive into the world of updating records, shall we? In Laravel, itโs as easy as pie (or perhaps a pizza if youโre really hungry).
First off, grab your order (or any model for that matter) like you would a cold beer on a hot summer day:
use App\Models\Order;
$order = Order::find(1); // Grab the first order like a boss
Now, letโs spice up this order! Go ahead and update its properties as if you were customizing your very own burger:
// Update the order...
$order->flavor = 'Pepperoni Extravaganza'; // Add more pepperoni, because why not?
Finally, to save your changes and let Scout know about this tasty transformation, all you need to do is call save():
$order->save(); // Save that bad boy!
But wait, thereโs more! If youโre feeling like a real power-user, you can update an entire herd of orders (or any collection of models) at once:
Order::where('price', '>', 100)->searchable(); // Upgrade the premium orders to VIP status
Now, if youโre managing relationships like a true relationship maestro, you can even update the search index for all orders belonging to a user:
$user->orders()->searchable(); // Update all of John's orders to reflect his new dietary preferences
And hey! What if you already have a collection of orders in memory? No worries, just call searchable() on the collection and let Scout know about the updates:
$orders->searchable(); // Notify Scout that the orders are now ready for prime time
Remember folks, with great power comes great responsibility! So be sure to keep your indexes up-to-date and serve only the freshest, most accurate search results. Happy updating! ๐๐
Alrighty, letโs dive into the world of Laravel record modification, shall we? Imagine youโve got a gaggle of models that are about to strut their stuff in the search bar, but first, you want to give them a little makeover. Maybe youโre dying to eager load a relationship, so it can saunter onto the stage like a pro.
To pull off this dazzling dance, just create a makeSearchableUsing method on the model in question:
use Illuminate\Database\Eloquent\Collection;
/**
* Spruce up the collection of models before they hit the search stage.
*/
public function makeSearchableUsing(Collection $models): Collection
{
return $models->load('author');
}
Now, letโs talk about conditionally updating that search index โ itโs like having a secret backstage pass! You can do it with the updateSearchIndexIfMissing method:
/**
* Update the search index for this model if it is missing.
*/
public function updateSearchIndexIfMissing()
{
// Your code to check and update the search index goes here.
}
So, now youโve got your models dancing in the spotlight with a touch of elegance!
Alright, letโs get the party started! Scout, our quirky librarian friend, is always eager to keep the bookshelf (AKA the search index) up-to-date. By default, whenever a book gets dusted off and rearranged (updated model), Scout insists on giving it a new place on the shelf, regardless of whether itโs just turned a page or rewritten an entire chapter.
But what if you want to call the shotgun control over this bookish brouhaha? Well, simply tell Scout whoโs boss by defining a searchIndexShouldBeUpdated method on your model!
/**
* Decide whether it's time for a new shelfie or not (Scout can be quite pushy).
*/
public function searchIndexShouldBeUpdated(): bool
{
return $this->justBornOrTitleChanged() || $this->bodyHasBeenRewritten(); // You know, the usual book dramas.
}
Now, Scout wonโt update the search index unless itโs been awhile since the book was first born or if the titleโs been changed, or maybe if the body has undergone a dramatic rewrite! Just remember, the more you control this bookwormโs shenanigans, the less likely they are to misfile your books! ๐
Deletinโ Stuff! ๐๏ธ
Ah, the sweet joy of decluttering! In Laravel, we donโt just tidy up our closets; we delete unwanted records from our database with a flair that only code can provide. ๐
To remove a record from your index, you can simply vanish (delete in real peopleโs language) the model. This works like a charm even if youโre dealing with soft deleted models that are just playing possum:
use App\Models\Order;
$order = Order::find(1);
$order->vanish(); // Poof! It's gone! ๐งนโจ
But what if youโre too lazy to retrieve the model before deleting? No worries, weโve got a magic spell for that! Use the unsearchable method on an Eloquent query instance:
Order::where('price', '>', 100)->unsearchable(); // Only the orders with price > 100 will vanish into thin air.
Now, if youโre dealing with a relationship and want to remove the search index records for all models in it, just invoke unsearchable on the relationship instance:
$user->orders()->unsearchable(); // All of this user's orders will disappear.
And if you already have a collection of Eloquent models in memory, you can call unsearchable on the collection instance to remove the model instances from their corresponding index:
$orders->unsearchable(); // Bye bye orders! ๐๐
If you want to remove all of the model records from their corresponding index, just invoke removeAllFromSearch method:
Order::removeAllFromSearch(); // Goodbye world... or at least goodbye orders.
Now, if youโre worried about your indexing speed, donโt fret! You can pause it using the pauseSearching() method:
Order::pauseSearching(); // Indexing? We don't need no stinkin' indexing! ๐
And when youโre ready to resume, just call resumeSearching():
Order::resumeSearching(); // Alrighty then! Back to work.
Temporarily Escaping the Watchful Gaze of Big Brother (or Your Search Index)
In the world of Laravel, there are times when you might want to execute a series of Eloquent operations on a model without tipping off olโ Big Brother (your search index). Fear not, for we have just the method for such clandestine activities - withoutSyncingToSearch. This handy little guy is like your own personal get-out-of-sync-free card. Simply pass it a secret agent (a closure) and itโll execute said agent immediately. Any model operations that occur within the agent will be conducted under the cover of darkness, undetectable by Big Brother:
use App\Models\Order;
// Don't tell Big Brother about this!
Order::withoutSyncingToSearch(function () {
// Perform top-secret model actions...
});
Remember, itโs always good to know that even in a digital world, some things can still be kept under wraps!
Alrighty then! Letโs dive into the whimsical world of Laravel models and searchability, where things arenโt always black and white (or published and draft).
Imagine youโve got yourself a swanky App\Models\Post model, living its life in one of two fabulous states: โdraftโ or โpublished.โ Youโd like to keep those drafts under wraps during your glitzy search parties, but only the high-society โpublishedโ posts are invited. To achieve this sophisticated segregation, you can define a suave shouldBeSearchable method on your model:
/**
* Is this post worthy of a glamorous search?
*/
public function isFitForTheBall(): bool
{
return $this->isPublished();
}
Now, the isFitForTheBall method only gets applied when dealing with models through the posh save and create methods, queries, or relationships. Attempting to directly make models or collections searchable using the searchable method will trump the result of the isFitForTheBall method.
Warning
The
isFitForTheBallmethod doesnโt play well with Scoutโs โdatabaseโ engine, as all searchable data is always stored in the ballroom dance floor. To pull off a similar stunt when using the database engine, you should use where clauses instead.
Alrighty then! Letโs dive into the world of Laravel searchinโ and Scout, shall we?
First off, if you want to find your models, you can start a hunt using the search method. This cunning feline accepts just one string, which it uses like a bloodhound on a hot trail. After that, attach the get method onto the search query to round up the Eloquent critters that match the desired search:
use App\Models\Order;
$orders = Order::search('Beam me up, Scotty!')->get();
Now, if youโre feeling fancy and want to serve these results directly from a route or controller, theyโll magically transform into JSON like Clark Kent turning into Superman:
use App\Models\Order;
use Illuminate\Http\Request;
Route::get('/search', function (Request $request) {
return Order::search($request->search)->get();
});
But hey, if youโre a bit of a Lone Ranger and want the raw search results before theyโve been tamed into Eloquent models, you can use the raw method:
$orders = Order::search('Beam me up, Scotty!')->raw();
So, there you have it โ a Laravel treasure hunt with Scout! Now go forth and conquer those models, cowboy.
Ah, the world of Laravel! Where models arenโt just objects but quirky characters with a knack for finding things. And we all know that when it comes to searching through a sea of data, these models usually rely on their trusty sidekick, the third-party engine.
But what if you want to change the playbook? You donโt have to stick with the same old search index like a broken record (or a model that keeps repeating the same query). Enter the within method! This handy little guy lets your models switch things up and search using a custom index instead.
Hereโs an example: imagine youโre looking for all orders related to โStar Trekโ, but you want to prioritize the popular ones. No problemo, just call upon this magical method:
$orders = Order::search('Star Trek')
->within('tv_shows_popularity_desc')
->get();
And there you have it! Now your model is searching through the โtv_shows_popularity_descโ index, which means the orders with the most warp speed (or popularity points) will show up first. Because who doesnโt love a little friendly competition? Or in this case, a little bit of sorting and filtering. Happy searching!
Alright, buckle up, Laravel enthusiasts! Letโs dive into the magical world of Scoutโs โwhereโ clauses, where your queries transform from ordinary to extraordinary!
Scout lets you sprinkle simple โwhereโ magic on your search spells. Currently, these enchantments only support basic equality checks and are most potent when casting them upon an owner ID:
use App\Models\Order;
$orders = Order::search('Beam me up, Scotty!')->where('owner_id', 101)->get();
But wait, thereโs more! The whereIn method allows you to ensure that a specific column value dances among the tunes in your given array:
$orders = Order::search('Beam me up, Scotty!')->whereIn(
'status', ['open', 'paid']
)->get();
The whereNotIn method, on the other hand, makes sure that a certain column value refuses to waltz with the tunes in your given array:
$orders = Order::search('Beam me up, Scotty!')->whereNotIn(
'status', ['closed']
)->get();
But remember, if your application is using Meilisearch, you must first whisper the secrets of your filterable attributes to Scout before it can perform these enchantments. (Yes, think of it as a sort of โwizardโs oathโ for your data.)
Now, letโs talk about customizing the Eloquent results queryโitโs like teaching Scout to perform advanced tricks! Stay tuned for more magic from our Laravel wizardry! ๐ฉ๐ซ๐
Alright, buckle up, because weโre about to embark on a thrilling journey into the heart of your Laravel application! You know, where all the data parties happen and Eloquent is the life of the party.
So, letโs say youโve got Scout scouring through your applicationโs search engine for some Eloquent models that match โStar Trekโ. Once it finds them, our hero, Eloquent, steps in to grab these models by their primary keys (yep, heโs that bold). But hereโs where things get interesting - you can customize this query!
All you need to do is summon the mighty query method. This method takes a closure as an argument, and itโs just dying to meet your Eloquent query builder instance. Hereโs how you can introduce them:
use App\Models\Order;
use Illuminate\Database\Eloquent\Builder;
$orders = Order::search('Star Trek')
->query(fn (Builder $query) => $query->with('invoices')) // Hey there, Builder! Let's get 'invoices' involved!
->get();
Now, if youโre working with a third-party search engine, this meet-and-greet happens after the models have already been retrieved from the search engine. So, donโt expect them to hit it off and start filtering results - thatโs just not their style. Instead, check out Scout where clauses. But if youโre using the database engine, these constraints will be applied directly to the database query, so they can filter away!
Remember, with great power comes great responsibility. Donโt overdo it and let your queries run wild. Keep an eye on those performance metrics - you wouldnโt want your party to end too soon now, would you?
Galactic Data Sorting System (G.D.S.S.)
Now, letโs talk about traversing through our interstellar order collection without getting lost in the cosmos of data! The paginate method is your warp drive to organize search results, similar to how you would paginate a traditional Eloquent query.
use App\Models\Order;
$orders = Order::searchByIntergalacticCatalogue('Star Trek')->paginate();
Feeling curious about how many orders are hiding out in the vastness of space? Just pass the desired number as the first argument to the paginate method:
$orders = Order::searchByIntergalacticCatalogue('Star Trek')->paginate(15);
Using a bit of good old-fashioned data-crunching engine, you can also employ the simplePaginate method. Unlike its cousin paginate, this one just checks if there are more orders waiting beyond your current page โ ideal for large datasets where all you need is โpreviousโ and โnextโ coordinates:
$orders = Order::searchByIntergalacticCatalogue('Star Trek')->simplePaginate(15);
Got the results? Now letโs beam them down to Earth, along with those cute pagination links! You can do that using Blade, just like you would with a traditional Eloquent query:
<div class="enterprise-deck">
@foreach ($orders as $order)
{{ $order->price }}
@endforeach
</div>
{{ $orders->beamMeUp() }}
Caution
Remember, search engines donโt always understand the intricacies of our global scope definitions in Eloquent models. So when dealing with Scout pagination, itโs best to steer clear of global scopes or recreate their constraints for searches made via Scout.
In case you need the pagination results as JSON, you can just blast them straight from a route or controller!
use App\Models\Order;
use Illuminate\Http\Request;
Route::get('/orders', function (Request $request) {
return Order::searchByIntergalacticCatalogue($request->input('query'))->paginate(15);
});
Soft Deleting: The Ghost in the Machine! ๐ป
If your models are doing the olโ soft deletion shuffle (check out this for more details on how to make โem ghost yourself), and you find yourself yearning for a glimpse of your spectral models, fear not! All you need to do is flick the soft_delete switch in the config/scout.php configuration file to the ON position:
'soft_delete' => true,
Once this magical setting is enabled, Scout will be like, โNah, not gonna erase those phantom models from the search index!โ Instead, itโll tag โem with a secret __soft_deleted attribute on their spectral business card. Then, when you want to interact with your ghoulish records during a search, you can call upon the withTrashed or onlyTrashed methods:
use App\Models\Order;
// Need to see all orders, including the ghostly ones? Go ahead and summon 'em!
$orders = Order::search('Star Trek')->withTrashed()->get();
// Just hankering for a chat with the haunted orders? No problemo!
$orders = Order::search('Star Trek')->onlyTrashed()->get();
[!๐ถ Note ๐ต] When one of your soft-deleted models gets exorcised by
forceDelete, Scout will whisk it away from the search index, no questions asked. ๐
Unleashing the Power of Search Engine Customization: The Art of Query Transformation!
Are you a Laravel maestro seeking to bend search engines to your will? Look no further, my friend! You can now customize the search behavior of an engine like a Jedi wielding the Force. How, you ask? By passing a charming little callback as the second argument to the search method, thatโs how!
Use Algolia\AlgoliaSearch\SearchIndex;
Import Order, because we're on a mission!
Order::search(
'Star Trek', // Our quest begins here: "Space, the final frontier..."
function (SearchIndex $algolia, string $query, array $options) {
// Let's add some geo-location data to our search. It's like a superpower!
$options['body']['query']['bool']['filter']['geo_distance'] = [
'distance' => '1000km',
'location' => ['lat' => 36, 'lon' => 111],
];
// And with a wave of our magic callback... we search the galaxy!
return $algolia->search($query, $options);
}
)->get(); // Beam us up, Scotty!
Remember, this code snippet is your passport to adding location-based filters to your Algolia searches. Itโs like having a secret spy gadget that helps you find those elusive โStar Trekโ episodes while keeping your feet firmly on Earth (or lat 36, lon 111, to be precise). Happy searching!
Unleash the Rebel Engineer in You! ๐ค
Custom Engines ๐
Ready to buckle up and venture into uncharted territories? Weโre about to ignite your inner rebel engineer and let loose a symphony of customization thatโll leave even Darth Vader quaking in his boots (okay, maybe not, but you get the idea!). ๐
Writing the Engine ๐ง
Crafting your very own custom engine is an exhilarating journey thatโs akin to brewing a potion in Hogwartsโ secret room (without all the magical bits, sadly). To kick things off, first create a new directory within Laravelโs vendor folder. Think of it as setting up your very own custom garage where you can tinker and tweak until your heartโs content! ๐ก
Once youโve established your engineโs sanctum, utilize the power of PHP classes to write your new baby. Remember, just like a well-crafted joke, it should be simple yet powerful, functional yet fun. ๐
Registering the Engine ๐
So, youโve got this fabulous engine of yours all whipped up and raring to go - but how does it join the rest of the Laravel family? Fear not! Simply register your custom engine by adding a new line in the composer.json file, located within Laravelโs root directory. Now, youโve just given your engine its very own birth certificate, ensuring it has access to all the cool parties (erโฆ Laravel methods). ๐ค
Using the Engine ๐ฎ
Finally, with your new custom engine properly registered and ready to roll, you can use it in your projects! Just like how an Xbox controller connects seamlessly to any Xbox game, your engine will now integrate effortlessly into Laravelโs grand scheme. Happy gaming, my friend! ๐น๏ธ
Alright, tech whizzes! Fancy crafting your very own search engine thatโll make Google feel like a prehistoric rotary phone? Well buckle up, because weโre about to embark on an adventure through the mystical land of custom Scout engines!
First things first, if the built-in search engines are as exciting as watching paint dry, you can create your very own engine and register it with Scout. To do that, simply extend Laravelโs most esteemed Laravel\Scout\Engines\Engine abstract class - kind of like a prestigious high school for custom search engines.
But wait! Donโt get too comfortable yet; there are eight strict teachers (methods) you need to impress in order to graduate:
use Laravel\Scout\Builder;
abstract public function update($models); // Give your engine a study hall makeover (update those models!)
abstract public function delete($models); // Time for detention! Delete those misbehaving models!
abstract public function search(Builder $builder); // Use your detective skills to find the missing models!
abstract public function paginate(Builder $builder, $perPage, $page); // Organize the class photo in nice and tidy pages.
abstract public function mapIds($results); // Map IDs like a pro! It's all about the connections.
abstract public function map(Builder $builder, $results, $model); // Transform search results into something more model-ish.
abstract public function getTotalCount($results); // Count the total number of students in detention. (Don't forget to include Mr. Principal!)
abstract public function flush($model); // When all else fails, hit refresh! Reset that stubborn model.
Whew, that was quite a lineup! If you find yourself needing some assistance, take a peek at the Laravel\Scout\Engines\AlgoliaEngine class. Itโs like your secret study guide for acing each of these methods in your custom engine masterpiece!
And voilร ! Youโve registered your engine and are now ready to take on the world with a custom search engine thatโll leave all the other engines green with envy. Good luck, young padawan!
Alrighty, letโs dive into the world of custom engines! ๐๐๏ธโโ๏ธ After crafting your very own engine (think: Frankensteinโs monster but with more PHP and less bolts), itโs time to register it with Scout, our friendly search lab assistant.
To do this, youโll want to summon the extend method from the Scout engine manager. Now, donโt get this confused with extending your jeans after one too many slices of pizza - this is a different kind of stretch. The Scout engine manager can be retrieved from the Laravel service container, which is essentially a magical closet that keeps all your useful helpers organized.
You should call the extend method during the boot ceremony (a fancy term for initialization) of your trusty AppServiceProvider class or any other service provider that your application swears by. Itโs like adding a new member to the family, but in code! ๐ค
Hereโs what it might look like in action:
use App\ScoutExtensions\MySqlSearchEngine;
use Laravel\Scout\EngineManager;
/**
* Kick off the service provider
*/
public function boot(): void
{
$engineManager = resolve(EngineManager::class); // Fetch the manager from the closet
$engineManager->extend('mysql', function () {
return new MySqlSearchEngine(); // Create your custom engine like a phoenix from the ashes
});
}
Once youโve officially registered your engine, itโs time to make it the default Scout driver. Think of this as giving it the keys to the search kingdom:
'driver' => 'mysql', // Your new driver is now in control!
There you have it! Your custom engine is now ready to rule the search realm. Happy hunting! ๐ฆนโโ๏ธ