Answer the question
In order to leave comments, you need to log in
How to create an Intermediary (middleware) to record User actions?
Kind everyone. I need to create a log of user actions. I have a CRUD controller, there is a route for each method, each route has its own name.
I want to implement a way to record user actions through middleware. If the user accessed the post.index route, then the user's id, the time, and the action 'View the list of posts' were recorded in the User_logs database.
So that the middleware has an array of routes with names:
[
post.index => 'View the list of posts',
post.create => 'Called the form to create a post',
post.store => 'Created a post',
etc. .
]
And depending on the route there was a record in the database.
Because I have a lot of controllers, I don't want to add a record of user actions to each method.
Answer the question
In order to leave comments, you need to log in
Here is my implementation:
public function handle(Request $request, Closure $next)
{
$routeName = $request->route()->getAction()['as'];
$routeDescription = [
post.index => 'Просмотр списка постов',
post.create => 'Вызвал форму для создания поста',
post.store => 'Создал пост',
];
if (array_key_exists($routeName, $routeDescription)) {
$a = $routs[$routeName];
UserLog::create([
'date' => '2021-08-25',
'user_id' => 2,
'action' => $a,
]);
}
return $next($request);
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question