How to create Laravel Cron job
We are share in this tutorial How to create Laravel Cron job you need this type of functionality in your Laravel application. it is working on a live server. but how to test in local we also mention in this tutorial. once you test in local and it works as per your requirement then no worry.
Step 1 : Create New Command Class
php artisan make:command CronJob
CronJob.php file automatic create in app/Console/Commands/ folder. so open it and simply place into it following code.
#app/Console/Commands/CronJob.php
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Str;//added
use DB;//added
class CronJob extends Command
{
protected $signature = 'CronJob:cronjob';//added
protected $description = 'User Name Change Successfully';//added
public function __construct()
{
parent::__construct();
}
public function handle()
{
\DB::table('users')
->where('id', 1)
->update(['name' => Str::random(10)]);//added
$this->info('User Name Change Successfully!');//added
}
}
?>
Step 2 : Change App\Console\Kernel.php
#App\Console\Kernel.php
<?php
namespace App\Console;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
class Kernel extends ConsoleKernel
{
protected $commands = [
'\App\Console\Commands\CronJob',//added
];
protected function schedule(Schedule $schedule)
{
$schedule->command('CronJob:cronjob')
->everyMinute();//added
}
protected function commands()
{
$this->load(__DIR__.'/Commands');
require base_path('routes/console.php');
}
}
?>
Step 3 : Test Cron Job In Local
php artisan CronJob:cronjob
Now you can run your command to change users table user name id = 1.
User Name Change Successfully