Search code examples
laravellaravel-6laravel-6.2

Where to use Event Logger Controller in Laravel


I create an Event Controller to log all the request to my APIs. I know that using a controller inside other controller is not a good idea, so... Where do I have to implement it?

EventController:

<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Event;

class EventController extends Controller
{
    protected static $instance = null;

    /** call this method to get instance */
    public static function instance(){
        if (static::$instance === null){
            static::$instance = new static();
        }
        return static::$instance;
    }

    /** protected to prevent cloning */
    protected function __clone(){
    }

    /** protected to prevent instantiation from outside of the class */
    protected function __construct(){
    }

    public function create($type, $description){
        Event::create([
            'id_type'       => $type,
            'date_time'     => date('Y-m-d H:i:s'),
            'id_users'      => auth()->user()->id,
            'description'   => $description       
        ]);
    }
}

Solution

  • 2 way i suggest:

    1.make an event and fire it in all actions. 2.make a middleware and add it in your each routing(or add in routegroup)

    Second one is better.because middlewares made exactly for this reason.All requests that sends to server should pass middleware first . In brief:you should create middleware with php artisan make:middleware yourMiddlewareName and after add your controller code in it you should add name of this middleware in kernel.php in middlewares array. Now its ready for assign it for every routes you want by append ->middleware("yourMiddlewareName") in end if each one.