# Laravel 9 Scout Full Text Search Tutorial (ok)

Hi Dev, Laravel 9 Scout Full Text Search Tutorial

In this tute, we will discuss laravel 9 scout full text search example. you can see laravel 9 scout search example. you will learn laravel 9 scout elasticsearch example. Here you will learn how to add full text search in laravel 9 scout. Let's get started with laravel 9 scout database engine example.

Laravel 9 provides Scout Package for full text search from your project. If you require to add full text search function in your laravel 9 application then you have to choose scout package to do.

In this example, we will install the scout composer package and use the database driver for full text search. then we will use scout with User model and add a name, email, and id column for full text search. let's see the below step to create full text search function.

![](https://www.itsolutionstuff.com/upload/laravel-9-scout-full-text.png)

**Step 1: Install Laravel 9**

This is optional; however, if you have not created the laravel app, then you may go ahead and execute the below command:

```
composer create-project laravel/laravel example-app
```

**Step 2: Install Scout**

In this step we have to install scout package and we will publish them:

```
composer require laravel/scout
```

Next, we have to publish our configuration file. so you need to run bellow command:

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

Now we need to set configuration database as driver in your env file:

.env

```
SCOUT_DRIVER=database
```

Read Also: [Laravel 9 Image Upload Example Tutorial](https://www.itsolutionstuff.com/post/laravel-9-image-upload-example-tutorialexample.html)

**Step 3: Update User Model**

Here, we already have users table created, so we need use "Searchable" and create toSearchableArray() method. so let's update following code:

app/Models/User.php

```
<?php  namespace App\Models;    use Illuminate\Contracts\Auth\MustVerifyEmail;use Illuminate\Database\Eloquent\Factories\HasFactory;use Illuminate\Foundation\Auth\User as Authenticatable;use Illuminate\Notifications\Notifiable;use Laravel\Sanctum\HasApiTokens;use Laravel\Scout\Searchable;   class User extends Authenticatable{    use HasApiTokens, HasFactory, Notifiable, Searchable;      /**     * The attributes that are mass assignable.     *     * @var array     */    protected $fillable = [        'name',        'email',        'password'    ];      /**     * The attributes that should be hidden for serialization.     *     * @var array     */    protected $hidden = [        'password',        'remember_token',    ];      /**     * The attributes that should be cast.     *     * @var array     */    protected $casts = [        'email_verified_at' => 'datetime',    ];      /**     * Get the indexable data array for the model.     *     * @return array     */    public function toSearchableArray()    {        return [            'name' => $this->name,            'email' => $this->email        ];    }}
```

Next, we will create some dummy records on users table and import it.

so let's run following commands:

Create Dummy Records:

[![](https://go.ezodn.com/charity/http/charity-ads.s3.amazonaws.com/charity_ads/1079/234x60.png)](https://go.ezodn.com/ads/charity/proxy?p_id=5cd53513-2d89-4e5a-6f38-829b7d69b292\&d_id=77568\&imp_id=2846957860100009\&c_id=1079\&l_id=10016\&url=https%3A%2F%2Fwww.directrelief.org%2Femergency%2Fukraine-crisis%2F\&ffid=1\&co=VN)

```
php artisan tinker  User::factory()->count(20)->create()
```

Import Records:

```
php artisan scout:import "App\Models\User"
```

**Step 4: Create UserController Controller**

In this point, now we should create a new controller as UserController. In this controller, we will add index method, that will return users with filter.

Let's update following code to your controller file:

app/Http/Controllers/UserController.php

```
<?php  namespace App\Http\Controllers;  use Illuminate\Http\Request;use App\Models\User;  class UserController extends Controller{    /**     * Display a listing of the resource.     *     * @return \Illuminate\Http\Response     */    public function index(Request $request)    {        if($request->filled('search')){            $users = User::search($request->search)->get();        }else{            $users = User::get();        }                  return view('users', compact('users'));    }}
```

**Step 5: Add Route**

In this is step we need to create route for listing users. so open your "routes/web.php" file and add following route.

routes/web.php

```
<?php  use Illuminate\Support\Facades\Route;  use App\Http\Controllers\UserController;  /*|--------------------------------------------------------------------------| Web Routes|--------------------------------------------------------------------------|| Here is where you can register web routes for your application. These| routes are loaded by the RouteServiceProvider within a group which| contains the "web" middleware group. Now create something great!|*/  Route::get('users', [UserController::class, 'index']);
```

**Step 6: Create View**

In Last step, let's create users.blade.php(resources/views/users.blade.php) for layout and we will write design code here and put following code:

**resources/views/users.blade.php**

```
<!DOCTYPE html><html><head>    <title>Laravel 9 Scout Full Text Search Tutorial - ItSolutionStuff.com</title>    <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.0.1/css/bootstrap.min.css" rel="stylesheet"></head><body>      <div class="container">    <h1>Laravel 9 Scout Full Text Search Tutorial - ItSolutionStuff.com</h1>      <form method="GET">        <div class="input-group mb-3">          <input             type="text"             name="search"             value="{{ request()->get('search') }}"             class="form-control"             placeholder="Search..."             aria-label="Search"             aria-describedby="button-addon2">          <button class="btn btn-success" type="submit" id="button-addon2">Search</button>        </div>    </form>      <table class="table table-bordered data-table">        <thead>            <tr>                <th>ID</th>                <th>Name</th>                <th>Email</th>            </tr>        </thead>        <tbody>            @foreach($users as $user)            <tr>                <td>{{ $user->id }}</td>                <td>{{ $user->name }}</td>                <td>{{ $user->email }}</td>            </tr>            @endforeach        </tbody>    </table></div>    </body>    </html>
```

**Run Laravel App:**

All the required steps have been done, now you have to type the given below command and hit enter to run the Laravel app:

```
php artisan serve
```

Now, Go to your web browser, type the given URL and view the app output:

Read Also: [Laravel 9 Drag and Drop File Upload with Dropzone JS](https://www.itsolutionstuff.com/post/laravel-9-drag-and-drop-file-upload-with-dropzone-jsexample.html)

```
http://localhost:8000/users
```

Output:

![](https://www.itsolutionstuff.com/upload/laravel-9-scout-full-text-2.png)

Maybe it can help you.....

<br>


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://learnphp.gitbook.io/learnphp/learn-lavarel/laravel-9-scout-full-text-search-tutorial-ok.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
