Rahadian Wiratama
Rahadian Wiratama

Reputation: 344

Laravel store JSON data API to database

I got the data json from API and I want to store them to my database.

data json sample :

{
    "success": true,
    "data": [
        {
            "status_employee_id": "1",
            "name": "Manager"
        },
        {
            "status_employee_id": "2",
            "name": "Staff"
        },
        {
            "status_employee_id": "3",
            "name": "OB"
        },
        {
            "status_employee_id": "4",
            "name": "Fired"
        },
        {
            "status_employee_id": "5",
            "name": "Retired"
        }
    ]
}

My model

class StatusEmployee extends Model
{
    use HasFactory;
    protected $table = 'status_employee';
    protected $fillable = [
       'status_employee_id','name'
    ];
    public $timestamps = false;

}

I have tried use this in my controller

public function store()
    {
        $client = new \GuzzleHttp\Client();
        $res = $client->request('GET', 'http://xx.xx.xx.xx/tools/public/get_status_employee');
        $datas = json_decode($res->getBody(), true);
        foreach($datas as $data){
            StatusEmployee::create([
                'status_employee_id' => $data->status_employee_id,
                'name' => $data->name,
            ]);
        }


    }

And I want to store the data json sample to my table status_employee. How to make it?

Upvotes: 0

Views: 853

Answers (2)

Martin Osusky
Martin Osusky

Reputation: 845

It's easy, Laravel Eloquent will do everything for you.

// If json is in string decode first
$data = json_decode($res->getBody(), true); // to array

// Eloquent approach
StatusEmployee::insert(@$data['data']); 

Upvotes: 3

Parakrama Dharmapala
Parakrama Dharmapala

Reputation: 1229

I assume you use Laravel since you have mentioned Laravel in your tags.

    DB::table('status_employee')->insert(json_decode($res->getBody(),true)['data']);

Upvotes: 1

Related Questions