DEV Community

yordadev
yordadev

Posted on

Logging Activity With Laravel and Pusher

LaravelEliteSquad

Logging activity is important for many reasons, I am not big on relying on packages and everyone and their brothers has a package for logging activity when it just isnt needed.

I am assuming you have laravel installed already writing this. If not, or you are not sure what Laravel is, head over to www.laravel.com and take a gander.

Before we can start, we need to require and install Pushers PHP SDK (https://pusher.com) which can be found at https://github.com/pusher/pusher-http-laravel

Installation

Require this package, with composer (https://getcomposer.org/), in the root directory of your project.

$ composer require pusher/pusher-http-laravel
Enter fullscreen mode Exit fullscreen mode

Add the service provider to config/app.php in the providers array. If you're using Laravel 5.5 or greater, there's no need to do this.

Pusher\Laravel\PusherServiceProvider::class
Enter fullscreen mode Exit fullscreen mode

If you want you can use the facade. Add the reference in config/app.php to your aliases array.

'Pusher' => Pusher\Laravel\Facades\Pusher::class
Enter fullscreen mode Exit fullscreen mode

Configuration

Laravel Pusher requires connection configuration. To get started, you'll need to publish all vendor assets:

$ php artisan vendor:publish --provider="Pusher\Laravel\PusherServiceProvider"
Enter fullscreen mode Exit fullscreen mode

This will create a config/pusher.php file in your app that you can modify to set your configuration. Also, make sure you check for changes to the original config file in this package between releases.

Finally to finish the Pusher portion head over to their website and grab your keys and place them into Laravel's .env file.

So to start, we need an event and model. So let us smash the following commands into our console.

php artisan make:event "LogActivity"
Enter fullscreen mode Exit fullscreen mode
php artisan make:model "UserActivity" --migration
Enter fullscreen mode Exit fullscreen mode

Now, lets set up the migration and model

Open App\UserActivity.php and put the following in it.

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class UserActivity extends Model
{
    protected $table = 'user_activities';

    protected $fillable = [
      'user_id',
      'type',
      'description',
      'archived'
    ];
}
Enter fullscreen mode Exit fullscreen mode

Open App\database\migrations\TimeStamp_create_user_activities.php and put the following in it.

<?php

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

class CreateUserActivitiesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
     public function up()
    {
        Schema::create('user_activities', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id');
            $table->string('type');
            $table->longText('description');
            $table->boolean('archived')->default(false);
            $table->timestamps();
        });
    }
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('user_activities');
    }
}
Enter fullscreen mode Exit fullscreen mode

Great, now we got our Model and Migration Setup, one last thing to do before we can start logging activity.

Open App\Events\LogActivity.php and put the following in it.

<?php

namespace App\Events;

use App\User;
use App\UserActivity;
use Pusher\Laravel\Facades\Pusher;
use Illuminate\Queue\SerializesModels;
use Illuminate\Foundation\Events\Dispatchable;

class LogActivity
{
    use Dispatchable, SerializesModels;
    public $user;
    public $type;
    public $description;
    public function __construct($user, $type, $description)
    {
        $this->data = [
            'user'        => $user, 
            'type'        => $type,
            'description' => $description,
            'now'         => \Carbon\Carbon::now()->toDateTimeString()
        ];
        $this->storeActivity();
        $this->broadcast();
    }
    private function storeActivity(){
        return UserActivity::create([
            'user_id'     => $this->data['user']->id,
            'type'        => $this->data['type'],
            'description' => $this->data['description']
        ]);
    }
    public function broadcast()
    {
        $this->data['user'] = $this->data['user']->name;
        return Pusher::trigger('staff-dashboard', 'logActivity', ['data' =>   $this->data]);
    }
}
Enter fullscreen mode Exit fullscreen mode

Just to break this event down some, storeActivity() is what performs the operation with the database and broadcast() is what relays the activity in real-time with Pusher to my admin dashboard, to create a real-time feed of the activity on my websites.

That it, your ready to start using it in action. Whenever you want to log activity you need to make sure you include the class by putting the following at the top of your controller.

use App\Event\LogActivity;
Enter fullscreen mode Exit fullscreen mode

Now to use it just drop the following:

event(new LogActivity(Obj $user, String $type, String $description));
Enter fullscreen mode Exit fullscreen mode

Here are some example use cases:

event(new LogActivity($user, 'Log', $user->name . ' logged in.'));

event(new LogActivity($user, 'Alert', $user->name . ' has sent you a message.'));

event(new LogActivity($user, 'Security', $user->name . ' is probing route user.support.'));
Enter fullscreen mode Exit fullscreen mode

I hope you enjoyed my first post on https://dev.to, let me know what you think or what you use, if it is similar to this.

Top comments (0)