4 steps to globally log your controller activities on Laravel

Julius LIMSON
May 29 · 3 min read

Logging are useful when auditing your system applications; it can help us identify weaknesses, vulnerabilities, and account our system activities which enables us to suggest improvements to the system.

Before we can start this exercise and to save time.I consider that we already created an existing Laravel-Project and should have a basic Knowledge of the framework; Link below:


Let’s Begin.

Step 1. Create a Migration and Model for the logger.

You can skip this step if you already have an existing model for this.

>php artisan make:model Logger -m

it will automatically create a model and a migration file which are located at

<project-folder>/app/Logger.php Default for the Model and

<project-folder>/database/migration/<date>-create_logger_table.php by default for the Migration

Edit the migration file to your liking. In my case and for simplicity, i just want to add the controller, action, user and some parameters for this exercise.

The Migration file up() function should be like this;

public function up() 
{
Schema::create('logger', function (Blueprint $table) {
$table->increments('id');
$table->string('method');
$table->string('controller');
$table->string('action');
$table->string('parameter');
$table->string('user');
$table->timestamps();
});
}

then start the migration.

>php artisan migrate

Your model should also look like this.

class Subscribers extends Model
{
protected $table = 'logger';
protected $fillable = ['controller','method','action','parameter','user'];
}

Step 2. Create a the class for the logger.

In this example the valule of $username I’m using is the \Session to showcase that it will work at the __constructor where we going implement.

You can also use the \Auth::user() in your user column if you like.

namespace App\Helpers; //<--1.)  pointed or any folder you likeuse App\Logger; // <--2.)  your Logger Model
use Session;
class Logger {static function addlog()
{
//this function is basically will add the the log to your database.
$route = explode("@", Route::getCurrentRoute()->getActionName());
$controller = $route[0]; // get controller
$action = $route[1]; // get action
$params = \Request::all(); // get url parameter
$username = \Session::get('UserName');//<-- can be ur Auth::user()
$log = new Logger();
$log->controller = $controller;
$log->action = $action;
$log->parameter = json_encode($params);
$log->user = $username;
$log->method = \Request::getMethod();
$log->save();
return $log->id;
}//end function
}//end Logger class

Now we have a fully functioning logger; we can now add it config app for easy call.

Step 3. Define the alias of your logger on your app config.

app config is located in <project-folder>/config/app.php by default.

in the aliases section of your config file.

Add this code below;

'Logger' => App\Helpers\Logger::class,

and it should look like this.

'aliases' => [
'Logger' => App\Helpers\Logger::class, <-- this one.
....
],

Step 4. Now apply the logger in the parent::controller to make it global.

To-Do this is simple; we must invoke the logger to your __contructor of your parent::Controller.

But we cannot call a session inside the __constructor of your parent::Controller(as this is a technical constraint of the framework). That’s why we have to do some tweaks before invoking the Logger;

in our Laravel-Project default app/Http/Controllers/Controller.php; We must add a __contructor(); OR Copy in a new File e.g.) MyController.php if you like;

then add code below;

public function __construct(){
$this->middleware(function ($request, $next) {
\Logger::addlog();
return $next($request);
});}

this code is basically injecting a middleware to our constructor before invoking the Logger. this will allow the constructor to call the session first before the logger. by this it will enable the session to be used inside the logger. I hope this makes sense.

By default the parent::controller is already extended by the child. if we created a copy of the parent controller. The child Controller should look like this.

class HomeController extends MyController {

Extending the parent Controller that we recently we created or edited on the child controller that we want to log. this will allow us to automatically log the actions to your database as defined.

Fin.

… github-incoming.