Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

imposition's avatar

Audit

Hi there! I made an Audit and it's working fine. But here is my problem. It's saving every single move my users make. I just want to save when they access an specific route For example I have the routes: /xxx /xxx1 /xxx2 /xxx3 I want my Audit only to make records about the /xxx3 url. Only when my user access /xxx3 then save into my DB

This is my model if it has any use:

use Illuminate\Database\Eloquent\Model;

class Audit extends Model
{

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'user_id', 'method', 'path', 'query', 'userAgent', 'ip', 'device' , 'platform', 'browser' , 'isDesktop', 'isMobile' , 'isPhone' , 'isTablet'
    ];


    public function user ()
    {
        return $this->belongsTo(User::class);
    }


    /**
     * Get online users
     *
     * @param int $min
     * @return \Illuminate\Database\Eloquent\Collection|static[]
     */
    public function online ($min = 3)
    {

        return $this->select('user_id')
                    ->where('audits.created_at', '>=', Carbon::now()->subMinutes($min)->toDateTimeString())
                    ->distinct('user_id')
                    ->with('user')
                    ->get()->map(function ($item) {
                        return $item->user;
                    });

    }
}
0 likes
6 replies
mushood's avatar

@imposition

You need to also show the code where you are calling the audit function.

However, to answer your question blindly, why not call it in the controller for your specific route?

imposition's avatar

@mushood I think what's making the whole thing work is this middleware:

<?php

namespace App\Http\Middleware;

use Closure;
use Jenssegers\Agent\Agent;
use App\Audit as Auditor;

class Audit
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {

        $agent = new Agent();


        if ( \Auth::check() ) {

            Auditor::create([
                'user_id'    => \Auth::user()->id,
                'method'     => $request->getMethod(),
                'path' => $request->getPathInfo(),
                'query'      => $request->getQueryString(),
                'userAgent' => $agent->getUserAgent(),
                'ip'        => \Request::ip(),
                'device' => $agent->device(),
                'platform' => $agent->platform(),
                'browser' => $agent->browser(),
                'isDesktop' => $agent->isDesktop(),
                'isMobile' => $agent->isMobile(),
                'isPhone' => $agent->isPhone(),
                'isTablet' => $agent->isTablet()
            ]);
        }

        return $next($request);
    }
}

What should i do to make it only work in specific routes? Like... I want it to only work in this routes

Route::get('/senhaf', ['middleware' => 'auth', 'uses' => 'SenhaFibraController@index']);
Route::get('/senhaw', ['middleware' => 'auth', 'uses' => 'SenhaWirelessController@index']);
Route::get('/senhaw/{rad}/edit', ['middleware' => 'auth', 'uses' => 'SenhaWirelessController@edit']);
Route::patch('/senhaf/{radius}', ['middleware' => 'auth', 'uses' => 'SenhaFibraController@update']);
Route::patch('/senhaw/{radius}', ['middleware' => 'auth', 'uses' => 'SenhaWirelessController@update']);
mushood's avatar

Taking from documentation: https://laravel.com/docs/5.5/middleware

Here are the steps briefly:

  1. Create Middleware
  2. Create logic in handle method
  3. Register the middles in routes middleware
  4. Assign middleware to a route

i believe you have step 1 and 2 done.

Step 3: a) Go to this file: app/Http/Kernel.php b) Add your middleware in the array below:

protected $routeMiddleware = [
    'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
    'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
    'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
    'can' => \Illuminate\Auth\Middleware\Authorize::class,
    'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
    'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
];

Step 4:

/* Once the middleware has been defined in the HTTP kernel, you may use the middleware method to assign middleware to a route:  */

Route::get('admin/profile', function () {
    //
})->middleware('auth');
/* You may also assign multiple middleware to the route:*/

Route::get('/', function () {
    //
})->middleware('first', 'second');
mushood's avatar

ITS THE CIA!

But just to check, please post your updated web.php file

imposition's avatar

Something like this:

Route::post('/senhaf/search', ['middleware' => 'auth', 'audit', 'uses' => 'SenhaFibraController@search']);
    protected $routeMiddleware = [
        'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
        'can' => \Illuminate\Auth\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
        'audit' => \App\Http\Middleware\Audit::class,

Please or to participate in this conversation.