Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

iSalam's avatar

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.

0 likes
4 replies
Ricus's avatar

Hi @isalam

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

iSalam's avatar

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?

Ricus's avatar
Ricus
Best Answer
Level 3

@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();

See https://laravel.com/docs/8.x/eloquent#inserting-and-updating-models for some more info on inserting.

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.

iSalam's avatar

Thanks @ricus. you elaborated the stuff really well. Hope I will make it work like you suggested. Thanks again!

1 like

Please or to participate in this conversation.