ryanborromeocodev's avatar

How to store the JSON response in my database using Guzzle?

I am using Guzzle to access an external API:

$api = new Client([
'base_uri' => 'https://www.space-track.org',
'cookies' => true, 
 ]); $api->post('ajaxauth/login', [
      'form_params' => [
         'identity' => 'myidentity', 
         'password' => 'mypassword', 
     ],
 ]);
 $response = $api-get('basicspacedata/query/class/boxscore/format/json');
  $mydata = json_decode($response->getBody()->getContents());
  $object = new Object();
  $object->COUNTRY = $mydata->COUNTRY;
  $object->SPADOC_CD = $mydata->SPADOC_CD
  $object->save();
return redirect('your/url',compact('object'));

With this I am able to access the API and display the JSON file on my webpage. Instead of doing this, what I want to do is to save the JSON result into my database and then display it from my own database.

I am able to seed a local JSON file, but I am unable to save the Guzzle result.

Is there anyway to save a Guzzle response JSON file into my database?

Here is the model and migration for the database:

MIGRATION

 Schema::create('operators', function (Blueprint $table) {
     $table->increments('id');
     $table->string('COUNTRY');
     $table->string('SPADOC_CD');
     $table->string('ORBITAL_TBA');
     $table->string('ORBITAL_PAYLOAD_COUNT');
     $table->string('ORBITAL_ROCKET_BODY_COUNT');
     $table->string('ORBITAL_DEBRIS_COUNT');
     $table->string('ORBITAL_TOTAL_COUNT');
     $table->string('DECAYED_PAYLOAD_COUNT');
     $table->string('DECAYED_ROCKET_BODY_COUNT');
     $table->string('DECAYED_DEBRIS_COUNT');
     $table->string('DECAYED_TOTAL_COUNT');
     $table->string('COUNTRY_TOTAL');
 });

MODEL

 protected $fillable = [
    'COUNTRY',
    'SPADOC_CD',
    'ORBITAL_TBA',
    'ORBITAL_PAYLOAD_COUNT',
    'ORBITAL_ROCKET_BODY_COUNT',
    'ORBITAL_DEBRIS_COUNT',
    'ORBITAL_TOTAL_COUNT',
    'DECAYED_PAYLOAD_COUNT',
    'DECAYED_ROCKET_BODY_COUNT',
    'DECAYED_DEBRIS_COUNT',
    'DECAYED_TOTAL_COUNT',
    'COUNTRY_TOTAL'
];
0 likes
3 replies
Cinek's avatar

Can you paste any errors appearing while saving?

All of your fields in migration are specified as "not null" so you should fill these field when you saving your model. Your model is called "Object" and your table in migration is "operators". Did you change table name in your model?

ryanborromeocodev's avatar

@Cinek I simply want to save the data fetched from the API to your database. Can you provide me example so that I can know what is the best way on how to implement this?

Please or to participate in this conversation.