Laravel: Cron Job Task Scheduling in order to Store Data from API Call in Database

Jokova
4 min readMar 22, 2020

--

Hello Developers! Hope this article finds you well these Corona Virus days we are getting through. Here in Greece, we are in quarantine for 10 days(~1 week) and we are keep going!

Laravel Cron jobs, DB, Api

Today I decided to talk you about cron jobs, simple data retrieving with api call and databases/migration/new table and data storage. All of these with my beloved Laravel Framework.

How to Create a Cron Job?

  1. Create New Command

First of all we will create a new command for our cron job, go to your project and run the command below:

php artisan make:command CakeCron — command=cake:cron

Now go to the command’s file → app/Console/Commands/CakeCron.php you will find code in it but we will write some extra code. :)

Notice that all the good ‘things’ will take place in the handle() function.

<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
class CakeCron extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'cake:cron'; /**
* The console command description.
*
* @var string
*/
protected $description = 'Cake Command Executed Successfully!';
//Description will be shown when the php artisan list command is executed.
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
\Log::info("Cake Cron execution!");
$this->info('Cake:Cron Command is working fine!');
}}

Your task schedule is defined in the app/Console/Kernel.php file's schedule method. Laravel Task Scheduler allows you to execute periodically a command. Let’s add some code in the Kernel.php

<?phpnamespace 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\CakeCron::class,
];
/**
* Define the application's command schedule.
*
* @param \Illuminate\Console\Scheduling\Schedule $schedule
* @return void
*/
protected function schedule(Schedule $schedule)
{
$schedule->command('cake:cron')
->hourly();
} /**
* Register the Closure based commands for the application.
*
* @return void
*/
protected function commands()
{
$this->load(__DIR__.'/Commands');
require base_path('routes/console.php');
}
}

As you can see, we told the kernel to run the command every hour.

Schedule Frequency Options (Laravel Website: see here)

Now we want to ensure that the above code/stuff works, so we need to run one of the commands below:

a) For test purposes, run one of the commands below:

php artisan schedule:runORphp artisan cake:cron

b) See the list of Laravel commands — Check if your new cron command included in this list.

php artisan list

To see if it works, navigate to logs: app/storage/logs/laravel-**-**-202*.log

Let’s go one step further.

Task Scheduling

When using the scheduler, you only need to add the following Cron entry to your server. You can find more about Task Scheduling in Laravel Documentation.

Starting the Laravel SchedulerGo to your terminal, cd into your project and run this command: crontab -eafter that press i in your keyboard in order to insert data, then paste the command below:* * * * * php /path-to-project/artisan schedule:run 1>> /dev/null 2>&1after that press ESC button and write :wq (if you want to save the changes)!!!*TIP*!!!: To get full path of your project, run pwd command.

Create a new Table in our Database

php artisan make:migration create_cake --create=cake

With the --create you create a new table in your database (don’t use --table).

Go to /database/migrations/2020_**_**_***_create_cake.php
and create the columns/fields of your new table!

<?phpuse Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateCake extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('cake', function (Blueprint $table) {
$table->bigIncrements('id');
$table->json('name')->nullable();
$table->dateTime('created_at');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::create('cake', function (Blueprint $table) {
$table->dropColumn('id');
$table->dropColumn('name');
$table->dropColumn('created_at');
});
}
}

After that run:

php artisan migrate

If you get any errors, go to .env file and check if DB_HOST=locahost change it to → DB_HOST=127.0.0.1

API Call & add data to Database

Now go to the command’s file → app/Console/Commands/CakeCron.php and add api call code:

a. Api Call

/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
$client = new \GuzzleHttp\Client();
$request = $client->get('https://url-to-api');
$response = $request->getBody()->getContents();
$cake = json_decode($response, true);
}

b. Add Data to Database’s new table

$published_at = \Carbon\Carbon::now();\DB::table(‘cake’)->insert([
[“json_data” => $response, “created_at” => “$published_at”]
]);

People, we get to the end of this article. If you have any further questions, please feel free to contact me. Kissez!

--

--

Jokova

Hello there! My name is Ioanna Vasdeki aka Jokova! I’m a passionate front-end developer </>. In my free time, I love cooking, getting outside & walking around!!