Fetch json data from api and display it as well as store it in DB table.
Hi I am working on Laravel project where I need to call API and display its data in the dashboard and store the data into the database table as well for future needs. I am able to get the data and pass it to view in the dashboard for display but unable to store it into a database table. Below is the index function of my controller that fetch the data from API.
public function index()
{
$user = Http::get('api url here")->json();
return view('users')->with([
'users' => $user
]);
}
Now I need help regarding storing data into database table. Any help would be appreciated.
There is a typo in your example but I'm assuming that is only for the post (single quote getting closed by a double quote)
With regards to your question, you will just need to create the relevant Model and migrations to store the data you want, and then persist it to the database whenever it makes sense for your application with normal Eloquent inserts
Thanks @Ricus
Yes, the typo here you can just ignore it (it was my mistake).
Thanks for your time. I have created a relevant Model. Can you share some sort of practical guide or boiler template or any other source which stores api data to already present database table?
@iSalam I don't know the structure of your api response, but since it's json laravel will convert that to an array for you with key=>values of everything in the json payload.
Now that you have the array, you can just assign the right values to your model, assuming they will be different as the API doesn't know of your db structure.
So if your model is called MyModel you can just do a simple:
$model = new MyModel();
$model->someField = $user['name'];
$model->someOtherField = $user['some other field'];
$model->save();
If you treat the api response as a simple array (which you already have using the Http facade), then the inserting should make more sense as you are just grabbing the info you want / need from the array.