In my Laravel project, I have a database that I get through an url. This database is in json. Following my project specification, I have to sotre the database in my local project, create a monthly cron in order to be up to date once by month.
Recover the datas is not so hard, but I have to create some seeder with this datas. is there a way to implement a monthly cron for database seeder like the way I use a monthly cron to be up to date with initail data ?
To be more specific, this is my cron to recover the initial data in my CronController.php
:
public static function updateJson(Request $request)
{
$type="application/json";
$charset="utf-8";
$path = 'database/market.json';
$time=filemtime($path);
$update=date("Y-M-d",$time);
$updateMonth= date('Y-M-d',strtotime('+1 month',strtotime($update)));
$now = date('Y-M-d');
if($now >= $updateMonth)
{
$data = file_get_contents('url/for/the/public/database');
$data = mb_convert_encoding($data, 'HTML-ENTITIES');
$res= file_put_contents($path, $data);
$whatIReallyNeed='update ok';
return response()->json($whatIReallyNeed)->header('Content-type', $type, 'charset', $charset);
} else {
$error = 'no need to update';
return response()->json($error)->header('Content-type', $type, 'charset', $charset);
}
}
For example I have a town table in my database, check the migration of this table:
class CreateTownTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('town', function (Blueprint $table) {
$table->increments('id');
$table->string('name', 255);
$table->timestamps();
$table->softDeletes();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('town');
}
}
And the seeder to register datas from the json database TownTableSeeder.php
:
public function run()
{
$path = "public/database/market.json";
// get contents of file
$json = file_get_contents($path);
// decode json datas
$datas = json_decode($json, TRUE);
// get the multi json array
$arrayFeatures = $datas["features"];
// define a new empty array
$arrayTown = array();
// populate the new array with values we need
foreach ($arrayFeatures as $feature) {
array_push($arrayTown, $feature["properties"]["commune"]);
}
// get unique entry for array
$results = array_unique($arrayTown);
// get only vales of array after do array_unique (no index)
$whatIReallyNeed = array_values($results);
foreach ($results as $result) {
DB::table('town')->insert([
'name' => $result,
]);
}
}
All of this works well, now I was wondering if i could launch the seeds migrations when the cron have updated the json database i store in my project.