Saturday, August 13, 2016

Create Your own command on Laravel 5.2


In Laravel application , when you try this command
 php artisan
you would see lots of command for laravel application. So if you want to create your own command, laravel provide you very easy way to do this. Here is the command you need.
 php artisan make:console
To use this command you have to provide a name for the class and you can also provide the name of the command that you want to use in command prompt. So here is the command to make a new command called log:demo
php artisan make:console LogDemo --command=log:demo
By running this command, laravel will create a class called LogDemo.class in app/console/commands directory. You can see that there is a protected variable called signature.  
 protected $signature = 'log:demo';
Here log:demo is the command that you will use on terminal Change the value of description variable as you like. Find handle function and add following line.
public function handle()
    {
        Log::info('i was here '.Carbon::now());
    }
When you run log:demo command, handle function will be executed. Here this line
Log::info('i was here '.Carbon::now());
Will create a line with current time on log file. Which is located on storage/logs directory. Now go to the app/console/kernal.php file. Add this
'App\Console\Commands\LogDemo',
string on commands variable. Finally execute php artisan log:demo and this will create a new string on log file. So every time you executed this command, new line will be added on log file.

0 comments:

Post a Comment