Laravel Scout Searchable

Laravel-Scout-Searchable

Hello there guys in this post I will show you how to implement Laravel Scout Searchable package to search your eloquent models. Now let’s begin. First, you need to watch this video on how to make a laravel blog using laravel-jetstream package.  Then you can proceed. If you already know how to create a blog or you’re an advanced Laravel developer then this is easy for you.

Laravel Scout is a powerful package that makes it easy to add full-text search to your Laravel applications. In this tutorial, you will learn how to use Scout to index and search your data, and how to customize the search experience to meet the needs of your users.

Whether you are building a simple blog or a complex e-commerce platform, Laravel Scout has you covered. By the end of this tutorial, you will have a solid understanding of how to use Scout to provide fast, reliable search functionality in your Laravel applications.

Step 1

Run the following command to install Laravel Scout…

composer require laravel/scout

Next, publish the Scout configuration file:

php artisan vendor:publish --provider="Laravel\Scout\ScoutServiceProvider"

Step 2

Run the following command to install a SeacrhController to handle search queries between your posts and the categories table.  This controller is set with the –invokable keyword method called when the controller is invoked.

php artisan make:controller SearchController --invokable

Step 3

When the controller is created go to it and update it with this code

public function __invoke(Request $request)
    {
        $posts = Post::search(trim($request->get('search')) ?? '')
             ->query(function($query) {
                $query->join('category_posts', 'posts.id', 'category_posts.post_id')
                      ->join('categories', 'category_posts.category_id', 'categories.id')
                      ->select(['posts.id', 'posts.title', 'posts.details', 'categories.name as category'])
                      ->orderBy('posts.id', 'DESC');
                   
             })
             ->get();
             return response()->json(data: $posts, status: 200);
    }
  • The __invoke method is a special method in Laravel that is called when an object is treated as a closure. In this case, the object is an instance of a class that represents an API endpoint for searching posts.
  • The code starts by calling the search method on the Post model, which performs a search based on the query string provided in the request. The trim function is used to remove any leading or trailing white space from the search query.
  • Next, the query method is called on the resulting collection of posts. This method allows you to define a custom query using the Eloquent query builder.
  • Inside the closure passed to the query method, the join method is used to perform an inner join between the posts and category_posts tables, and another inner join between the category_posts and categories tables. This allows you to retrieve data from all three tables in a single query.
  • The select method is used to specify which columns should be retrieved from the tables. In this case, the id, title, and details fields from the posts table, and the name field from the categories table are selected.
  • Finally, the get method is called on the query to execute it and retrieve the results. The results are then returned as a JSON response to the client.

Step 4

.env file

Update .env file with this

SCOUT_DRIVER=database

The SCOUT_DRIVER environment variable is used to configure the search driver for Laravel Scout, which is a package that provides a simple, driver-based solution for adding full-text search to your Laravel applications.

The value of the SCOUT_DRIVER environment variable is set to the name of the search driver that you want to use. In this case, the value is set to database, which indicates that the search functionality should be implemented using a database.

Step 5

Post.php Model

Update the post model with the following

Use Searchable; (place it below Use Factory)

Place this at the bottom

public function toSearchableArray()
{
return [
  'title' => '',
  'details' => '',
  'categories.name' => '',
     ];
}

This code is defining the toSearchableArray method on a model in a Laravel application. The purpose of this method is to specify which fields of the model should be included in the search index when using Laravel Scout.

The toSearchableArray method returns an array of key-value pairs, where the keys represent the fields that should be included in the search index, and the values represent the values of those fields. In this case, the title, details, and categories.name fields are all included in the search index.

Step 6

Search Now

If all goes well which it should. Search for anything within your models.

http://127.0.0.1:8000/search?search=post

Sign up for free tutorials in your inbox.

We don’t spam! Read our privacy policy for more info.

Leave a Comment

Your email address will not be published. Required fields are marked *