How to create (Laravel) How to create (Laravel),
The Artisan command comes with a lot of features, but also to other original command allows you to create.This time, I will show you how to create an original Artisan command and how to register it in Laravel’s command scheduler for executing the created command periodically .
By combining these two functions, you can easily implement batch processing such as executing processing at a fixed time every day.Also, the original command you created can be easily executed from the console like other Artisan commands, which is convenient when you want other developers to use your program.
How to create (Laravel), table of contents
Artisan Creating an original command
1.1 Generating a command class
1.2 Implementing an original command
1.3 Executing a command
Registering the original command in the command scheduler
2.1 Registering the schedule
2.2 Enabling the command scheduler
Output the command execution result to a log file
How to create (Laravel), Creating Artisan original commands How to create (Laravel),
By creating an Artisan original command, you can execute any process you have implemented from the console and command scheduler.In this article, I will create a command to get the number of users registered in the User table on the database every minute.
Command class generation How to create (Laravel),
First, generate a command class to describe the processing of the original command .
The command class can be automatically generated based on the template prepared from the beginning by executing the Artisan make: command command.Move to #Laravel project (PROJECT_NAME)
cd ~ / html / laravel / PROJECT_NAME
# Generate a command class for the original command
Php – 7.1 Artisan Make : Command UserCountCommand
This time, the class name is UserCountCommand because it is a command to get the number of users registered in the User table.
If successful, a command class file will be created directly under app / Console / Commands /.
How to create (Laravel), Implementation of original command How to create (Laravel),
Since the command class generated in 1.1 is empty with no processing written , enter the command name and arbitrary processing .
Open the UserCountCommand file for administrative user registration with a text editor and edit it.app / Console / Commands / UserCountCommand.php<? phpphp
namespace App \ Console \ Commands ;
use Illuminate \ Console \ Command ;
use App \ User ;
class UserCountCommand extends Command
* The name and signature of the console command.
* @var string
protected $ signature = ‘user: count’ ;
* The console command description.
* @var string
protected $ description = ‘Command description’ ;
* Create a new command instance.
* @return void
public function __construct ()
parent :: __construct ();
* Execute the console command.
* @return mixed
public function handle ()
// Message to output to standard output or log
$ message = ‘[‘ . date ( ‘Ymd h: i: s’ ) . ‘] UserCount:’ . User :: count ();// Output message at INFO level
$ this- > info ( $ message );
First, we will operate on the User table.use App \ User; App \ User ;
Is loading the User model.nextrotected $ signature =’user: count’;= ‘user: count’ ;
For the part, set the variable $ signature to the name of the command.
The name of the command is arbitrary, but use something that is easy to remember.How to create (Laravel),
Finally, write the processing when the command is executed in the handle () method.I’m calling the User :: count procedure to look up information in the User table on the database, which uses Laravel’s Eloquent ORM feature.I won’t explain about Eloquent ORM this time, but it is a very convenient function that allows you to refer to, register, update, and delete tables without writing SQL.You can also output the message with echo, but this time we will use the standard output method
$ this-> info () provided in the command class
.In addition to $ this-> info () in the command class, $ this-> error () for error output and $ this-> table (which automatically formats into a table layout by passing an array) ) And other convenient methods for standard output are provided.After creating the command class, execute the following command under PROJECT_NAME to make Laravel recognize the created command class, and reconfigure the autoload .php-7.1 ../composer.phar dump-autoload- 7.1 ../ Composer . Phar Dump – AutoloadLaravel uses Composer’s autoloading mechanism, which automatically loads the required files.As you proceed with development with Laravel, the error “Class <file name> does not exist” may occur in various situations such as when a new file is added.
If you get the above error, try reconfiguring the autoload first.
How to create (Laravel), Command execution
Try executing the original command created in 1.2 from the console.php-7.1 artisan user: count- 7.1 Artisan User : Count
The execution result is output to standard output.
If successful, a message similar to the following will be displayed in green text.
Register the original command in the command scheduler How to create (Laravel),
Laravel has a feature called Command Scheduler .The command scheduler is a function for executing a certain command periodically (repeatedly executing it at a fixed date and time).If you are using a Linux server, it is popular to use Cron on the server to set periodic execution, but Laravel has a command scheduler function that is more convenient than Cron, so let’s use that.
How to create (Laravel), Schedule registration How to create (Laravel),
First, register the command you want to execute periodically and the schedule to execute it in the command scheduler.This time, let’s add a schedule to execute the original command created in 1. every minute.app / Console / Kernel.php<? phpphp
namespace App \ Console ;
use Illuminate \ Console \ Scheduling \ Schedule ;
use Illuminate \ Foundation \ Console \ Kernel as ConsoleKernel ;
class Kernel extends ConsoleKernel
* The Artisan commands provided by your application.
* @var array
protected $ commands = [
\ App \ Console \ Commands \ UserCountCommand :: class
* Define the application’s command schedule.
* @param \ Illuminate \ Console \ Scheduling \ Schedule $ schedule
* @return void
protected function schedule ( Schedule $ schedule )
// Run the user: count command every minute
$ schedule- > command ( ‘user: count’ )-> everyMinute ();
* Register the commands for the application.
* @return void
protected function commands ()
$ this- > load ( __DIR__ . ‘/ Commands’ );
require base_path ( ‘routes / console.php’ );
There are two places to add in total.First, specify the information of the command class created in 1. in the array $ commands.
Note that it ends with the class name :: class.Next, enter the schedule you want to execute the command in the schedule method.
The $ schedule-> command (‘user: count’) part specifies which command to execute, and
the-> everyMinute () part specifies the date and time to execute.The everyMinute method is set to be executed every minute, but other detailed execution timing settings similar to Cron are possible, so the typical ones are introduced below.Run every hour
$ schedule-> hourly ();$ Schedule-> daily (); run every day at 12:00$ Schedule-> dailyAt (‘5: 15′); run at a specified time every day$ Schedule-> monthlyOn (25, ’23: 55’); run at the specified date and time every month ;You can also specify it in the same way as Cron
$ schedule-> cron (‘* * * * * *’);
How to create (Laravel), Enabling the command scheduler How to create (Laravel),
I registered the schedule in 2.1, but the command scheduler is not yet enabled by this alone.
Laravel’s command scheduler uses Cron’s features behind the scenes, so you need to add a setting to enable Artisan’s command scheduler in crontab.In order to enable Laravel’s command scheduler, you need to add the following settings to crontab.* * * * * / usr / local / bin / php-7.1 /usr/home/ <username> / html / laravel / PROJECT_NAME / artisan schedule: run * * * * / Usr / Local / Bin / Php – 7.1 / Usr / Home / <user name> / Html / Laravel / PROJECT_NAME / Artisan Schedule : Run
On the shared rental server “ACE01”, you cannot edit the Cron table directly, so follow the procedure below to use the “Script Periodic Execution Tool”.In “Script periodic execution tool”, you must specify the file when registering the periodic execution schedule. (You cannot write the command to execute directly)To do this, first create a PHP file (do_cron.php) to execute the commands to execute the Artisan command scheduler.do_cron.php<? phpphp
exec ( ‘/ usr / local / bin / php-7.1 /usr/home/ <username> / html / laravel / PROJECT_NAME / artisan schedule: run’ );
The exec function can execute command line external commands from PHP. Also, at this time, please specify the absolute path for PHP and Artisan.After creating the file, log in to the control panel of the server and set the “Script Scheduled Execution Tool” to periodically execute the file created earlier.If you select “Public site settings”-> “Script periodic execution tool”, the following setting screen will be displayed.Please refer to the photo and set as follows.For “New registration”, select the file (do_cron.php) created earlier.
Select 7.1 or higher for “PHP version”
Select “Execution schedule” to be every minute
After making all the selections, click the “Add” button.
The command scheduler is now enabled and the commands will be executed periodically according to the schedule registered in 2.1.
How to create (Laravel), Output the command execution result to a log file How to create (Laravel),
Looking back on the steps up to this point, the original command created in 1. is now executed periodically in 2.However, as it is now, the commands that are periodically executed by the command scheduler are executed in the background, so the execution result cannot be known.
I also don’t know if it completed successfully or if an error occurred.This is inconvenient, so let’s create a log file that records command execution results and errors and set it to output the results to that file.Laravel’s command scheduler also provides methods for outputting log files.app / Console / Kernel.php~ Omitted ~
protected function schedule ( Schedule $ schedule )
// Execute the user: count command every minute to output to the log file
$ schedule- > command ( ‘user: count’ )-> everyMinute ()
-> appendOutputTo ( storage_path ( ‘logs / user_count.log’ ) );
~ Omitted ~
To output the log file, use the appendOutputTo method.
The appendOutputTo method adds if the file already exists, and creates a new one if it does not exist.
If you want to create a new log file for each execution instead of appending, use the sendOutputTo method instead of the appendOutputTo method.A log file user_count.log is created in storage / logs /.
Make sure that the command execution result is described every minute.
How to create (Laravel), Finally How to create (Laravel),
In this article, I introduced how to create Artisan’s original command and set up the command scheduler. Web applications often implement batch processing by periodic execution, so let’s master Laravel’s command scheduler and aim to improve development efficiency.