I have the following middleware to record the user action into the user_action_logs table.
<?php
namespace App\Http\Middleware;
use App\Models\UserAccessLog;
use Carbon\Carbon;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Symfony\Component\HttpFoundation\Response;
class UserAccess
{
/**
* Handle an incoming request.
*
* @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next
*/
public function handle(Request $request, Closure $next): Response
{
$user_id = null;
if (Auth::check()) {
$user_id = Auth::user()->id;
}
$now = Carbon::now()
->format('Y-m-d H:i:s');
UserAccessLog::create([
UserAccessLog::USER_ID => $user_id,
UserAccessLog::IP_ADDRESS => $request->ip(),
UserAccessLog::PATH => $request->path(),
UserAccessLog::QUERY_STRING => $request->getQueryString(),
UserAccessLog::DATE_AND_TIME => $now,
]);
return $next($request);
}
}
Then let's see the table how the user action log is recorded.
> select * from user_access_logs;
+----+---------+--------------+------+--------------------------------------------------------------+---------------------+
| id | user_id | ip_address | path | query_string | date_and_time |
+----+---------+--------------+------+--------------------------------------------------------------+---------------------+
| 1 | NULL | 192.168.65.1 | / | keyword=engineer&philippine_province_ids%5B0%5D=0722&salary= | 2024-03-08 09:23:02 |
+----+---------+--------------+------+--------------------------------------------------------------+---------------------+
1 row in set (0.000 sec)
Well, looked working fine. But when I opened the page that includes livewire component, the following records were appeared.
| 6 | 9b8367e7-5f0c-414f-972c-ad37f98b7d0b | 192.168.65.1 | dashboard/personnel/applications | NULL | 2024-03-08 09:37:51 |
| 7 | 9b8367e7-5f0c-414f-972c-ad37f98b7d0b | 192.168.65.1 | livewire/update | NULL | 2024-03-08 09:38:19 |
The first record was that when I opened the page of livewire component. The second one was that when I turn on the radio. And after that any actions on the livewire component was recorded as '/livewire/update'.
OK, I have updated the middleware not to record '/livewire/update'.
if ($request->path() !== 'livewire/update') {
$now = Carbon::now()
->format('Y-m-d H:i:s');
UserAccessLog::create([
UserAccessLog::USER_ID => $user_id,
UserAccessLog::IP_ADDRESS => $request->ip(),
UserAccessLog::PATH => $request->path(),
UserAccessLog::QUERY_STRING => $request->getQueryString(),
UserAccessLog::DATE_AND_TIME => $now,
]);
}
But how can I record the operation on the livewire component in a smart way?
Thanks in advance.