Make your Laravel project modular pt. 3 define scheduling
Hi there, It’s been a long time since my last post in January. I am so sorry, because I have some of work that I can’t leaving. In this post I’m still talk about modularization in Laravel, in the case I want to share about define or registering our schedule, policy and middleware in our module. Why we do that? Let’s say that if we want to create a schedule, base on Laravel documentation we need to register our schedule in Kernel.php
and it will work fine without any trouble, but what if the project is worked by several people that each people work on its his module and registering his schedule in the same place (Kernel.php
)? Most likely it will produce a conflict, so registering schedule in the module itself is one of the solution that can fix the problem.
Prequisite
You must already have a Laravel module project, find more about laravel module in here.
Schedule
First of all, we need to create our command and then register it to schedule. To make a command you can use the following command php artisan module:make-command YourCommandName YourModuleName
and it will generate your command in your module, for example we will create command to delete blogs in every start of month so we can make it by this way php artisan module:make-command DeleteBlogsCommand Blog
and it will create the DeleteBlogsCommand
in the Blog
module.
After modify the command, we can register our command in the BlogServiceProvider
and it will be look like this pict :
Then see if it already registered with php artisan
command.
After the comand registered as well, let’s register our command as a schedule in our Blog
module. We can see the list schedule of our application with php artisan schedule:list
command
We can register the schedule in BlogServiceProvider
using this in the boot
function :
use Illuminate\Console\Scheduling\Schedule;$this->app->booted(function () {
$schedule = $this->app->make(Schedule::class);
$schedule->command(‘blog:delete-all’)
->monthly();
});
And if we run php artisan schedule:list
again it will show this :
Last but not least we can configure our crontab in server to run the php artisan schedule:run
so our schedule will be run in every month. Or you can use the php artisan schedule:work
command for running the schedule locally.
Thats all that I can share about define scheduling in laravel module, thanks for read my post. Maybe in the next post I will share about define policy in laravel modules, if you have any question or suggestion please feel free to leave comments below. Share with others if you found this post useful.
See ya
Project
References