Looking to store a JSON response from an external API (using Guzzle) into mySQL database. A lot of what I've done so far is based on this question/answer
Storing parts of API data to database
I've got a model, controller and migration setup. The plan is to setup a CRON job that runs daily and calls for the new data from the API.
Right now, I just want to store the data into a database (I can setup the CRON job later).
Is there anything I'm missing here or any mistakes in my code? I had a route setup before but I don't know if that's applicable?
**EDIT
Nothing is being stored in the database when running this.
Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Rating extends Model
{
protected $fillable = ['ratingId', 'ratingName', 'ratingKey', 'ratingKeyName', 'schemeTypeId'];
}
Controller
I've got two functions going on here. The first is consuming the external API. The second function is storing it into the database.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use GuzzleHttp\Client;
use App\Rating;
class GuzzleController extends Controller
{
public function getRatings()
{
$client = new Client([
'url' => 'https://api.ratings.food.gov.uk/ratings'
]);
$request = $client->request('GET', [
'headers' => [
'x-api-version' => '2',
'Accept' => 'application/json'
]
]);
$ratings = json_decode($request->getBody()->getContents(), true);
return $ratings;
}
public function saveRatings()
{
$ratings = $this->getRatings();
collect($ratings)
->each(function($rating, $key) {
Rating::create([
'ratingid' => $rating['ratingid'],
'ratingName' => $rating['ratingName'],
'ratingKey' => $rating['ratingKey'],
'ratingKeyName' => $rating['ratingKeyName'],
'ratingTypeId' => $rating['ratingTypeId']
]);
});
}
}
Migrations
Just setting up the table here.
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateRatingsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('ratings', function (Blueprint $table) {
$table->bigIncrements('id');
$table->integer('ratingId');
$table->string('ratingName');
$table->string('ratingKey');
$table->string('ratingKeyName');
$table->integer('schemeTypeId');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('ratings');
}
}