First post! New to php & Laravel, figured I'd learn by creating a test project. I've been following Laracasts for guidance but run into issues.
What I'm looking to achieve:
- Utilise Guzzle to call for an API
- Store response into mySQL database
- Setup a route for this
- Setup a schedule so the controller runs once a day on schedule (I can start a new thread if need be)
I've got a controller setup for the Guzzle & storing data. I've got a database created which works as intended. The route I'm unsure about though on what exactly needs to be done so I'm struggling here on how to actually run the controller and store the data in the database.
I'd appreciate if anyone could review my code if I've done anything wrong, and give some guidance on routes in context of this.
Controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use GuzzleHttp\Client;
class DataController extends Controller
{
public function index()
{
$client = new Client(['base_uri' => 'https://api.ratings.food.gov.uk/ratings']);
$response = $client->request('GET', [
'headers' => [
'x-api-version' => '2',
'Accept' => 'application/json'
]
]);
$mydata = json_decode($response->getBody()->getContents(), true);
$object = new Object();
$object->ratingId = $mydata->ratingId;
$object->ratingName = $mydata->ratingName;
$object->ratingKey = $mydata->ratingKey;
$object->ratingKeyName = $mydata->ratingKeyName;
$object->schemeTypeId = $mydata->schemeTypeId;
$object->save();
Requests::insert($object);
}
}
?>
Migration
<?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->timestamps();
$table->integer('ratingId');
$table->string('ratingName');
$table->string('ratingKey');
$table->string('ratingKeyName');
$table->integer('schemeTypeId');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('ratings');
}
}
API JSON Response Example
{
"ratings": [
{
"ratingId": 12,
"ratingName": "5",
"ratingKey": "fhrs_5_en-gb",
"ratingKeyName": "5",
"schemeTypeId": 1,
"links": [
{
"rel": "self",
"href": "http://api.ratings.food.gov.uk/ratings/12"
}
]
},
{
"ratingId": 11,
"ratingName": "4",
"ratingKey": "fhrs_4_en-gb",
"ratingKeyName": "4",
"schemeTypeId": 1,
"links": [
{
"rel": "self",
"href": "http://api.ratings.food.gov.uk/ratings/11"
}
]
},
{
"ratingId": 10,
"ratingName": "3",
"ratingKey": "fhrs_3_en-gb",
"ratingKeyName": "3",
"schemeTypeId": 1,
"links": [
{
"rel": "self",
"href": "http://api.ratings.food.gov.uk/ratings/10"
}
]
}
}
Requests::insert($object);$json=json_decode($rating->content);