Laravel 11 Custom User Logs Activity Example

Hello, laravel web developer! In this article, we'll see how to create custom user logs activity in laravel 11. Here, we'll create activity logs in laravel 11 without a package. Previously we'd use spatie/laravel-activitylog. 

We'll create custom log tables and a helper facade to track user logs. Also, you can customize it as per your requirements.

Laravel 11 Custom User Logs Activity

Laravel 11 Custom User Logs Activity

 

Step 1: Install Laravel 11

In this step, we'll install laravel 11 using the following command.

composer create-project --prefer-dist laravel/laravel user-activity-logs

 

Step 2: Configure Database

Then, configure the database in the .env file.

.env

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel-11
DB_USERNAME=root
DB_PASSWORD=

 

 

Step 3: Create LogActivity Table and Model

Next, create a migration and model using the following command.

php artisan make:migration create_log_activity_table

Migration:

<?php
  
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
  
return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up(): void
    {
        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();
        });
    }
  
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down(): void
    {
        Schema::dropIfExists('log_activities');
    }
};

Then, migrate the table into the database using the following command.

php artisan migrate

Next, create a model using the following command.

php artisan make:model LogActivity

app/Models/LogActivity.php

<?php


namespace App\Models;


use Illuminate\Database\Eloquent\Model;


class LogActivity extends Model
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'subject', 'url', 'method', 'ip', 'agent', 'user_id'
    ];
}
 
Step 4: Create LogActivity Helper Class

Then, create a LogActivity helper class and define the logic of user activity.

app/Helpers/LogActivity.php

<?php


namespace App\Helpers;
use 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 Helper Class

Next, register the Helper class as a facade in the configuration file. So, let's open app.php and define the facades.

config/app.php

'aliases' => [

	....

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

]
 
Step 6: Define Route

Now, define the routes into the web.php file.

routes/web.php

Route::get('add-to-log', 'LogController@addToLog');
Route::get('activity-logs', 'LogController@activityLog');
 
Step 7: Crete Controller

Next, define the function in the LogController.php. So, add the following code to that file.

app/Http/Controllers/LogController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;


class LogController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {


    }
    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function addToLog()
    {
        \LogActivity::addToLog('Add To Log Test');
        dd('log insert successfully.');
    }


    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function activityLog()
    {
        $logs = \LogActivity::logActivityLists();
        return view('activity-logs',compact('logs'));
    }
}
 
Step 8: Create View File

Then, create a blade file to display activity logs.

resources/views/activity-logs.php

<!DOCTYPE html>
<html>
<head>
	<title>Laravel 11 Custom User Logs Activity Example - Techsolutionstuff</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>Laravel 11 Custom User Logs Activity Example - Techsolutionstuff</h1>
	<table class="table table-bordered">
		<tr>
			<th>No</th>
			<th>Subject</th>
			<th>URL</th>
			<th>Method</th>
			<th>Ip</th>
			<th width="300px">User Agent</th>
			<th>User Id</th>
			<th>Action</th>
		</tr>
		@if($logs->count())
			@foreach($logs as $key => $log)
			<tr>
				<td>{{ ++$key }}</td>
				<td>{{ $log->subject }}</td>
				<td class="text-success">{{ $log->url }}</td>
				<td><label class="label label-info">{{ $log->method }}</label></td>
				<td class="text-warning">{{ $log->ip }}</td>
				<td class="text-danger">{{ $log->agent }}</td>
				<td>{{ $log->user_id }}</td>
				<td><button class="btn btn-danger btn-sm">Delete</button></td>
			</tr>
			@endforeach
		@endif
	</table>
</div>


</body>
</html>

 

Step 9: Run Laravel 11 Application

Now, run the laravel 11 application using the following command.

php artisan serve

 


You might also like :

techsolutionstuff

Techsolutionstuff | The Complete Guide

I'm a software engineer and the founder of techsolutionstuff.com. Hailing from India, I craft articles, tutorials, tricks, and tips to aid developers. Explore Laravel, PHP, MySQL, jQuery, Bootstrap, Node.js, Vue.js, and AngularJS in our tech stack.

RECOMMENDED POSTS

FEATURE POSTS