Skip to content

Instantly share code, notes, and snippets.

@aniket-magadum
Last active April 4, 2024 15:36
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aniket-magadum/9e56e4d888587c4632bc9bfc712586c1 to your computer and use it in GitHub Desktop.
Save aniket-magadum/9e56e4d888587c4632bc9bfc712586c1 to your computer and use it in GitHub Desktop.
Command Finished Event In Laravel

Steps for logging a command in Laravel.

First we will create a custom command which we will run to demonstrate the logging

php artisan make:command CustomCommand 

Also we will create a model and migration file together

php artisan make:model -m CommandLog

Then, just need to listen to the CommandFinished event which runs after every command and insert the log using the model. Please go throw the files below.

<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('command_logs', function (Blueprint $table) {
$table->id();
$table->json('command_with_arguments');
$table->json('options');
$table->smallInteger('exit_code');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('command_logs');
}
};
<?php
namespace App\Providers;
use App\Models\CommandLog;
use Event;
use Illuminate\Console\Events\CommandFinished;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*/
public function register(): void
{
//
}
/**
* Bootstrap any application services.
*/
public function boot(): void
{
Event::listen(CommandFinished::class, function (CommandFinished $event) {
CommandLog::create(
[
'command_with_arguments' => json_encode($event->input->getArguments()),
'options' => json_encode($event->input->getOptions()),
'exit_code' => $event->exitCode,
]
);
});
}
}
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class CommandLog extends Model
{
use HasFactory;
protected $fillable = ['command_with_arguments','options','exit_code'];
}
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
class CustomCommand extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'app:custom-command';
/**
* The console command description.
*
* @var string
*/
protected $description = 'This is a custom command to demonstrate command logging in Laravel.';
/**
* Execute the console command.
*/
public function handle()
{
$this->info("This is a custom command which does nothing of value.")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment