yaskatir's avatar

How can I save the JSON data to the database?

I'm using a Google Place API package and I want to get the reviews of the place. And to store this data in the database so that there is no need to call the API on every page visit.

I get the JSON response perfectly, but I don't know how to save the different values to the database. I don't want to save the entire JSON response, only the ones I need, e.g. review text, author name, avatar img etc. This is my controller:

public function index()
{
    $response = \GoogleMaps::load('placedetails')
	 ->setParam ([
		  'placeid' =>'***',
		  'reviews_no_translations' => 'true',
		  'reviews_sort' => 'newest'     
	])
 	->get();

 	$reviews = collect(json_decode($response, true));
    return view('contact', compact('reviews'));
}

Thank you in advance for your help :)

0 likes
5 replies
jlrdw's avatar

I suggest make related tables. Storing json is a bad idea.

Mikegk's avatar

How about using the JSON Type in your Schema?

//Example Schema
Schema::create('items', function (Blueprint $table) {
            $table->id();
            $table->json('data')->nullable();
            $table->timestamps();
        });

From here you could simply save as json string...

martinbean's avatar

@yaskatir You should probably check if you can do this first. I’m betting it’ll be against Google’s terms and conditions to scrape data like this.

yaskatir's avatar

Wow, thank you for this quick reply :))

I don't want to store the JSON, just the values of the JSON.

Let's say that there is a value "author_name" : "David" in the JSON, I would like to insert this into the author_name row of the table, and so on with the other data resulting from the review.

chiefguru's avatar

@yaskatir my colleague likes to write artisan commands to do this sort of data manipulation as the source isn't always as complete as you'd like. So basically call the API, pull in the data, disassemble, re-assemble and write to the DB either directly or via Models.

The beauty of doing it this way is that you can then simply schedule the command to run regularly to keep things up to date.

I've also used this process to cache exchange rates, so that we don't have to make an API call every time someone makes a purchase.

Please or to participate in this conversation.