Black Friday: coupon FRIDAY24 for 40% off Yearly/Lifetime membership! Read more here

Filament: Log Search Queries to the Database

2024-11-13

When we add a search to our Tables, it would be cool to know what people are searching for, right? So, let me show you how to log the searches into the DB.


Creating Search Logs Model

First, we need a place to store our search logs:

Migration

Schema::create('search_logs', function (Blueprint $table) {
$table->id();
$table->string('resource');
$table->string('search_query');
$table->foreignId('user_id')->constrained('users');
$table->timestamps();
});

Then, we can add a Model:

app/Models/SearchLog.php

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
 
class SearchLog extends Model
{
protected $fillable = [
'resource',
'search_query',
'user_id',
];
 
public function user(): BelongsTo
{
return $this->belongsTo(User::class);
}
}

Logging Table Search

Now, we can work on logging the Table searches by adding additional logic to a method:

app/Filament/Resources/UserResource/Pages/ListUsers.php

use Illuminate\Database\Eloquent\Builder;
use App\Models\SearchLog;
 
// ...
 
protected function applyColumnSearchesToTableQuery(Builder $query): Builder
{
if ($this->getTableSearch()) {
// Injecting Search Log creation
SearchLog::create([
'search_query' => $this->getTableSearch(),
'resource' => static::$resource,
'user_id' => auth()->id(),
]);
}
 
// Return to normal function execution
return parent::applyColumnSearchesToTableQuery($query);
}

By adding this method to our List Page - we can intersect the search query and log it without changing how the function works.


Logging Global Search

We can also add Global search logging as required:

app/Filament/Resources/UserResource.php

use Illuminate\Support\Collection;
use App\Models\SearchLog;
 
// ...
 
public static function getGlobalSearchResults(string $search): Collection
{
if ($search) {
// Injecting Search Log creation
SearchLog::create([
'search_query' => $search,
'resource' => static::class,
'user_id' => auth()->id(),
]);
}
 
// Return to normal function execution
return parent::getGlobalSearchResults($search);
}

Adding this to our Resource - we can log a global search query before returning the results.

So, now you have all the searches in the database and you may later create a separate Log Viewer for them.

This tutorial's code comes from our Project Example Log Search Queries and Display Log Table

A few of our Premium Examples: