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:
Hello developers! Today, we're about to embark on a journey to elevate our Laravel applications by integrating...
Feb-12-2024
In this article, we will see the laravel 9 left join query example. laravel 9 left join eloquent returns all rows from t...
Mar-31-2022
This article will show us how to validate max file size using javascript. Many times we have a requirement to check...
Aug-03-2020
In this example, we will learn how to run a specific seeder in laravel 8. If you want to run only one seeder in laravel...
Jan-19-2022