If you have many searchable resources, you can log what people looked for to gain more insights into your application.
To log our searches, we first need a table:
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();});
And 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); }}
Once these are in place, we can work on creating our reusable Trait to log the search queries:
Next, we will create: