Power of Flutter A Guide to Creating and Using Extensions

Creating Custom User Log Activity in Laravel (Versions 6-11)

Share this post on:

Introduction

Looking to manage user activity logs in Laravel without relying on external packages? In this guide, we’ll walk you through creating a custom user log activity system tailored for Laravel versions 6 through 11. Learn how to set up custom log tables and helper facades to seamlessly track user activities within your application.


Why Create Custom User Logs in Laravel?

Managing user logs is essential for maintaining security and monitoring activities in your Laravel application. By creating a custom logging system, you gain complete control over how logs are recorded, stored, and displayed.

  • Customization: Tailor the log table structure to meet your specific needs, including fields for user IDs, IP addresses, and HTTP methods.
  • No External Dependencies: Keep your application lightweight and maintainable by avoiding third-party packages.
  • Scalable Solution: This method is scalable and can be easily integrated into existing or new Laravel projects.

Step-by-Step Implementation

Step 1: Install a Fresh Laravel Application

Start by installing a new Laravel project:

composer create-project --prefer-dist laravel/laravel laravel_log

Step 2: Configure the Database

Set up your database configuration in the .env file:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_log
DB_USERNAME=root
DB_PASSWORD=root

Step 3: Create LogActivity Migration and Model

Create a log_activities table to store your logs:

php artisan make:migration create_log_activity_table --create=log_activities

In the migration file, define the schema:

Schema::create('log_activities', function (Blueprint $table) {
$table->increments('id');
$table->string('subject');
$table->string('url');
$table->string('method');
$table->string('ip');
$table->string('agent')->nullable();
$table->integer('user_id')->nullable();
$table->timestamps();
});

Run the migration:

php artisan migrate

Step 4: Create the LogActivity Helper Class

This class will handle log creation and retrieval:

namespace App\Helpers;

use Illuminate\Support\Facades\Request;
use App\Models\LogActivity as LogActivityModel;

class LogActivity
{
public static function addToLog($subject)
{
$log = [];
$log['subject'] = $subject;
$log['url'] = Request::fullUrl();
$log['method'] = Request::method();
$log['ip'] = Request::ip();
$log['agent'] = Request::header('user-agent');
$log['user_id'] = auth()->check() ? auth()->user()->id : 1;
LogActivityModel::create($log);
}

public static function logActivityLists()
{
return LogActivityModel::latest()->get();
}
}

Step 5: Register the Helper Class

Register the helper class in config/app.php:

'aliases' => [
// other aliases
'LogActivity' => App\Helpers\LogActivity::class,
],

Step 6: Define Routes

Add routes to manage logs in routes/web.php:

Route::get('add-to-log', 'HomeController@myTestAddToLog');
Route::get('log-activity', 'HomeController@logActivity');
Route::delete('log-activity/{id}', [HomeController::class, 'deleteLogActivity']);

Step 7: Update HomeController

Implement methods in HomeController to add and display logs:

public function myTestAddToLog()
{
LogActivity::addToLog('My Test Log Entry');
dd('Log inserted');
}

public function logActivity()
{
$logs = LogActivity::logActivityLists();
return view('logActivity', compact('logs'));
}

public function deleteLogActivity($id)
{
LogActivityModel::find($id)->delete();
return redirect()->back()->with('success', 'Log deleted successfully');
}

Step 8: Create the Log Activity View

Create logActivity.blade.php to display logs:

<!DOCTYPE html>
<html>
<head>
<title>Log Activity Lists</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" />
</head>
<body>
<div class="container">
<h1>Log Activity Lists</h1>
@if(session('success'))
<div class="alert alert-success">{{ session('success') }}</div>
@endif
<table class="table table-bordered">
<!-- Table contents -->
</table>
</div>
</body>
</html>

Step 9: Testing

Run your Laravel application:

php artisan serve

Visit the following URLs to test your log system:

  • http://localhost:8000/add-to-log
  • http://localhost:8000/logActivity

Conclusion

Creating a custom user log activity system in Laravel gives you full control over log management without the need for external packages. By following this guide, you can implement a scalable, maintainable solution that enhances security and monitoring in your Laravel applications.

For more Laravel tutorials, visit the Laravel documentation and explore additional resources on log management.

Related Blog Post

If you’re interested in enhancing the security of your Laravel applications, check out our guide on Integrating Two-Factor Authentication in Laravel. It covers everything you need to know to add an extra layer of security to your app.