Search

How to make Custome Log System in Laravel?

post-title

In this article, I will share with you how to make a custom log system in your laravel application. when you work with a very large application and a number of actions accrue in an application then the log is the most important part. because of we will track all the action or system activity as log formate.

Here I will share with you step by step how to implement a log system from scratch.

Step - 1 : Create Laravel Application.

First, we need to create fresh laravel application help of the following command in your terminal. or continue with the existing applications.

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

Step - 2 : Setup Database Setting.

Now, we configure Database setting in .env file.

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

Step - 3 : Create Migration.

In the next step, we need to create a migration for logs table.

php artisan make:migration create_log

Now open the created migration file and write the following code into it.

database/migrations/2019_09_09_070253_create_logs.php

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateLog extends Migration {

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up() {
        Schema::create('logs', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('subject', 255);
            $table->text('query_request')->nullable();
            $table->string('query_type', 255)->default('general');
            $table->integer('transaction_id')->nullable();
            $table->string('url', 255);
            $table->string('method', 255);
            $table->string('ip', 255);
            $table->string('agent', 255)->nullable();
            $table->integer('user_id')->nullable();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down() {
        Schema::dropIfExists('logs');
    }

}

Now, running the laravel migration help of the following artisan command to create by default tables.

php artisan migrate

Step - 4 : Create Log Helpers

Now, we need to create Log.php a file in app a folder. simply write the following code into it.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Log extends Model
{
    
    protected $table = 'logs';
    protected $guarded = array();

function addToLog($subject, $queryRequest, $queryType)
{
    if($queryRequest != NULL){
        $queryRequest = json_encode($queryRequest);
    }

    $log = [];
    $log['subject'] = $subject;
    $log['query_request'] = $queryRequest;
    $log['query_type'] = $queryType;
    $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 : 0;

    static::create($log);

    return true;
}

Step - 5 : How to Use in Controller

Now, I will show you how to use this log functionality in your controller. here we add log in a database when a new user registers on our laravel application. but you can used it everywhere in your laravel application. just pass three main parameters.

<?php

namespace App\Http\Controllers\Auth;

use App\Log;
use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use App\User;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;

class RegisterController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Register Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles the registration of new users as well as their
    | validation and creation. By default this controller uses a trait to
    | provide this functionality without requiring any additional code.
    |
    */

    use RegistersUsers;

    /**
     * Where to redirect users after registration.
     *
     * @var string
     */
    protected $redirectTo = RouteServiceProvider::HOME;

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest');
    }

    /**
     * Get a validator for an incoming registration request.
     *
     * @param  array  $data
     * @return \Illuminate\Contracts\Validation\Validator
     */
    protected function validator(array $data)
    {
        return Validator::make($data, [
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
            'password' => ['required', 'string', 'min:8', 'confirmed'],
        ]);
    }

    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array  $data
     * @return \App\User
     */
    protected function create(array $data)
    {
        // Add log in database
        Log::addToLog('General Log.', $data, 'Register');

        return User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => Hash::make($data['password']),
        ]);
    }
}

this is one simple example, but you can use log in everywhere in your laravel application. like user edits the profile, user changes the password, etc...

i hope you like this article.