Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel-5 Separate model for each log table

I am currently developing an application with Laravel 5, my main tables are users, suppliers, manufacturers etc.

Each of these tables has a separate users_log,suppliers_log log table. The purpose of these log tables is to review operations performed for a single entity (for example: logs belonging to a particular manufacturer and the changes made in the past for that manufacturer etc.,)

I am planning to use Eloquent and I have generated an Eloquent model for each of the major tables.

My Question : Should I generate separate Eloquent models for each of the log tables or just write a method like user_log() in the model of the major table to write my log.

P.S : Number of users going to use my application are few, therefore writing logs to a database is preferred over file logs.

like image 236
Magesh Kumaar Avatar asked Oct 19 '22 13:10

Magesh Kumaar


1 Answers

I would only use a logs table, because logs should be something simple/generic/straightforward.

These are the logs table columns I would use:

  • id
  • user_id (User that performed the action we're logging)
  • action (description of the action performed: deleted user, updated supplier, created manufacturer, etc)
  • url (the URL used to perform the action)
  • ip (IP address of the user)
  • timestamps

With that in mind, you would then have a standard pivot table for each loggable table type, which in your case would be log_manufacturer, log_supplier and log_user (I'm following the Laravel table naming convention here, but go ahead and use other names if you wish).

This way you can do a global search by any kind of log:

$logs = Log::where('user_id', 1)->get(); // get all logs of User 1

by specific log type (user, supplier, manufacturer, etc):

$logs = Log::has('suppliers')
            ->where('user_id', 1)
            ->get(); // get Supplier logs created by User 1

or get all specific models filtered by a Log:

$manufacturers = Manufacturer::whereHas('logs', function ($query)
{
    $query->where('user_id', 1);
})
->get(); // get all Manufacturers that have been manipulated by User 1

In order to create a new entry on the logs table, I would then use Model Observers so that at each created, updated or deleted action it would handle the creation transparently.

like image 164
Quetzy Garcia Avatar answered Oct 22 '22 03:10

Quetzy Garcia