Hi there! You're in the right place if you’ve ever wanted to automate repetitive tasks in your Laravel application. Laravel 11 makes it super simple to schedule tasks with its built-in task scheduling system. Whether it’s sending daily emails, clearing logs, or syncing data, you can handle it without messing around with traditional cron job files.
In this guide, I’ll walk you through how to create and set up cron jobs in Laravel 11. By the end of this tutorial, you’ll have a solid understanding of how to automate tasks efficiently in your application.
Laravel 11 Cron Job Task Scheduling Example
In this step, we'll install the laravel 11 application using the following command.
composer create-project laravel/laravel example-app
Next, we'll create a command using the following command.
php artisan make:command DemoCron --command=demo:cron
app/Console/Commands/DemoCron.php
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Http;
use App\Models\User;
class DemoCron extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'demo:cron';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Command description';
/**
* Execute the console command.
*/
public function handle()
{
info("Cron Job running at ". now());
$response = Http::get('https://jsonplaceholder.typicode.com/users');
$users = $response->json();
if (!empty($users)) {
foreach ($users as $key => $user) {
if(!User::where('email', $user['email'])->exists() ){
User::create([
'name' => $user['name'],
'email' => $user['email'],
'password' => bcrypt('123456789')
]);
}
}
}
}
}
Then, we'll register the command in the console.php file.
routes/console.php
<?php
use Illuminate\Support\Facades\Schedule;
Schedule::command('demo:cron')->everyMinute();
Now, run the scheduler using the following command.
php artisan schedule:run
Next, we'll set cronjob on the server. You need to install crontab on the server. If you are using Ubuntu Server, then it is already installed.
crontab -e
Now, add the following line to the crontab file.
* * * * * cd /path-to-your-project & php artisan schedule:run >> /dev/null 2>&1
You might also like:
In this article, we will see how to add a foreign key in laravel 10 migration. Here, we will learn about laravel 10...
May-05-2023
Hello All, In this tutorial i will show you laravel 8 mobile number OTP authentication using firebase, There are many...
Mar-31-2021
In this article, we will see how to validate international phone numbers using jquery. Here, we will learn about mo...
May-12-2023
In this example, I will show you how to implement/install data tables in laravel. Datatables provides users with many fu...
May-16-2020