Optimize Your Project with Laravel Searchable: Setup and Best Practices

Laravel offers several tools to build robust and scalable web applications. One such tool that significantly enhances user experience is Laravel Searchable. It allows you to add robust search functionality, enabling users to quickly find what they’re looking for.

In this blog, we’ll help you learn what exactly Laravel Searchable is and how it works. We’ll also dive into how Laravel development experts set up and use Laravel Searchable in their projects. So, with that, let’s start.

What is Laravel Searchable?

Laravel Searchable is a feature that allows you to implement search functionality within your Laravel application. It provides a simple and efficient way to search through various models and attributes in your database, making it easy to retrieve and display relevant data to your users.

Laravel Searchable is not a package itself but rather a concept that can be achieved using various packages and techniques. However, there is a popular package called spatie/laravel-searchable that provides a simple way to add search functionality to your Laravel models.

The spatie/laravel-searchable package allows you to make your models searchable by adding a Searchable trait and implementing a getSearchResult method. This method returns a SearchResult object that contains the model instance, a title, and a description.

With Laravel Searchable, you can search through multiple models and attributes using a single search query. You can also customize the search logic to handle different models and relationships effectively.

How Laravel Searchable Works?

Laravel Searchable works by adding a trait to your models. This trait provides methods for performing searches on the model’s data. You can customize which columns are searchable and how the search is performed by overriding methods in the trait.

Here is a basic example of how to use Laravel Searchable:

Step 1: First, install the package using the composer command:

composer require spatie/laravel-searchable

Step 2: Add the trait to the model where you want the search functionality implemented:

use spatie\Searchable\SearchableTrait;
class Product extends Model
{
    use SearchableTrait;
    protected $searchable = [
        'columns' => [
            'products.name' => 10,
            'products.description' => 5,
        ],
    ];
}

Step 3: Once done, perform a search in your model using the command:

$results = Product::search('keyword')->get();

This was the overview of how to use Laravel Searchable in your project. Now let’s begin with how professional Laravel developers set up and use it in their models.

Struggling to make your Laravel website functionally interactive?

How to Set Up and Use Laravel Searchable in your Project?

Setting up Laravel Searchable in your Laravel site is straightforward. Here’s a stepwise guide to set up Laravel Searchable on your website using spatie/laravel-searchable package:

Prerequisites:

  • PHP: Ensure you have PHP installed on your system, preferably version 8.1 or later.
  • Composer: Composer is a dependency manager for PHP. Install it if you haven’t already.

Step 1: Create Laravel Project

First, open your terminal or command prompt and then navigate to your desired project directory. After that, run the following command to create a new Laravel project:

laravel new your-project-name

Replace your-project-name with your desired project name. Then navigate into the project directory using the cd command:

cd your-project-name

Step 2: Install the Laravel Searchable Package

Run the following Composer command in your terminal to install the package:

composer require spatie/laravel-searchable

This will download the package and make it available for your site. The Spatie Laravel Searchable package is developed by Spatie and is regularly updated, ensuring compatibility with Laravel’s latest versions.

Step 3: Publish Configuration

Laravel Searchable comes with a configuration file that you may want to publish if you need to customize certain aspects of the package. Use this command to publish the configuration file:

php artisan vendor:publish --provider="Spatie\Searchable\SearchableServiceProvider"

This command will generate a searchable.php configuration file in your config directory, allowing you to set custom options for the package.

Step 4: Define Your Searchable Models

After configuration, you can define which models should be searchable by creating searchable rules. The general process involves specifying the fields within each model that the search functionality should target.

Start by defining a model that will be searchable. Let’s say you have a Product model that you want users to search through.

use Spatie\Searchable\Searchable;
use Spatie\Searchable\SearchResult;
class Product extends Model implements Searchable
{
    public function getSearchResult(): SearchResult
    {
        $url = route('products.show', $this->id);
        return new SearchResult(
            $this,
            $this->name,
            $url
        );
    }
}

Step 5: Specify Searchable Fields

You can define which fields within your model should be searchable. This step helps create the search functionality to only specific columns, such as name and description for a Product model.

Step 6: Creating a Search Class

To handle searches across multiple models or fields, create a search class. This class will serve as the main point for running search queries across defined models. So, create a new Search class, such as App\Search\ProductSearch and define which models and fields should be part of this search.

use Spatie\Searchable\Search;
$searchResults = (new Search())
    ->registerModel(Product::class, 'name', 'description')
    ->perform('query');

The perform() method will then execute the search based on the provided query string.

Step 7: Performing a Search

You’ll typically handle searches in a controller, using the Search class provided by Laravel Searchable. Here’s an example in a to controller method:

public function search(Request $request)
{
    $searchTerm = $request->input('query');
    $searchResults = (new Search())
        ->registerModel(Product::class, 'name', 'description')
        ->registerModel(User::class, 'name', 'email')
        ->perform($searchTerm);
    return view('search.results', compact('searchResults'));
}

This example shows a search across multiple models (Product and User) with different fields (name, description, email).

Step 8: Display Results in a View

Pass the $searchResults to your view and loop through them to display each result. Here the code you can use:

@foreach ($searchResults as $result)
    <h2>{{ $result->searchable->name }}</h2>
    <p>{{ $result->searchable->description }}</p>
@endforeach

This approach ensures that each result is displayed in the view with its associated fields.

By following above steps, you’ll have a basic search functionality set up in your Laravel application using the spatie/laravel-searchable package. This setup allows you to search across multiple models and customize the search results as needed. If you want to create a dynamic, interactive and robust site, get in touch with our Laravel development services.

Tips to Optimize Performance for Laravel Searchable

Optimizing the performance of Laravel Searchable is crucial, especially when dealing with large datasets. Here are some tips to help you improve the performance of your search functionality:

Indexing Searchable Columns

Indexing is one of the most effective ways to improve search performance. Ensure that the columns you are searching are indexed in your database.

ALTER TABLE products ADD INDEX name_index (name);
ALTER TABLE products ADD INDEX description_index (description);

Use Full-Text Search

If your database supports full-text search (e.g., MySQL, PostgreSQL), you can leverage this feature to improve search performance and relevance. Here is the code for MySQL and PostgreSQL respectively:

ALTER TABLE products ADD FULLTEXT INDEX name_description_index (name, description);

Or

CREATE INDEX name_description_index ON products USING gin (to_tsvector('english', name || ' ' || description));

Caching Search Results

Caching search results can significantly reduce the load on your database and improve response times. It is especially used for frequently searched queries. Here is how you can use the Laravel’s cache facade:

use Illuminate\Support\Facades\Cache;
$query = 'keyword';
$cacheKey = 'search_results_' . md5($query);
$results = Cache::remember($cacheKey, 60, function () use ($query) {
    return Product::search($query)->get();
});

Paginate Search Results

Paginating search results can help reduce the amount of data processed and returned in a single request. That can result in improved performance and user experience. To paginate results you can use the code:

$results = Product::search('keyword')->paginate(10);

Limit the Number of Searchable Columns

Only include the columns that are necessary for your search functionality. Limiting the number of searchable columns can reduce the complexity and improve the performance of your search queries.

protected $searchable = [
    'columns' => [
        'products.name' => 10,
        'products.description' => 5,
    ],
];

Use Laravel Scout for Advanced Search

For more advanced search capabilities and better performance, consider using Laravel Scout in combination with Laravel Searchable. Laravel Scout provides a simple, driver-based solution for adding full-text search to your Eloquent models. To use Laravel Scout firstly install it using the composer command:

composer require laravel/scout
After that add the scout trait to your model:
use Laravel\Scout\Searchable;
class Product extends Model
{
    use Searchable;
    protected $searchable = [
        'columns' => [
            'products.name' => 10,
            'products.description' => 5,
        ],
    ];
}

By following the above tips, you can optimize the performance of Laravel Searchable. If you are looking to customize your site design and functionality consider hiring Laravel developers.

What is the Difference Between Laravel Scout and Laravel Searchable?

Laravel Scout and Laravel Searchable are both tools that enhance search functionality in Laravel sites. But they serve different purposes and are optimized for different scenarios. Here is quick difference:

FeatureLaravel ScoutLaravel Searchable
PurposeFull-text search with advanced capabilitiesSimple, database-driven searches
IntegrationIntegrates with external search engines (e.g., Algolia, MeiliSearch)Works directly with Eloquent models
Use CaseIdeal for large datasets and complex search requirementsSuitable for smaller applications with basic search needs
Setup ComplexityRequires configuration and external servicesEasy to set up, no external dependencies
PerformanceOptimized for speed and scalabilityBest for moderate datasets, performance may vary
FeaturesCustom ranking, filtering, search suggestionsCustomizable queries on Eloquent models

Use Laravel Scout for websites that require advanced search features, scalability, and integration with external search engines. On the other hand, use Laravel Searchable for sites with simple search requirements and a preference for a self-contained solution. If you want to develop a website with the right tools and best practices followed, consider hiring our Laravel development company.

Need expert assistance with your Laravel project?

Wrapping Up

Setting up and using Laravel Searchable can significantly enhance your application’s search functionality. By installing the package, adding the Searchable trait to your models, and customizing searchable columns, you can have basic search functionality.

Additionally, optimizing performance through indexing, caching, and paginating search results ensures your application remains robust. Integrating with Laravel Scout or external search engines like Algolia can further enhance search capabilities.If you are looking to build a site that is robust and well-designed, hire Laravel developers.

author
Mayur Upadhyay is a tech professional with expertise in Shopify, WordPress, Drupal, Frameworks, jQuery, and more. With a proven track record in web development and eCommerce development.

Leave a comment