Home > Back-end >  how to make an laravel 8 API for saving an array of objects
how to make an laravel 8 API for saving an array of objects

Time:02-24

{owner: '456123', holders: Array(2)}

holders:

0: { equipments: 'test', release_by: 'test'}

1: {equipments: 'test', release_by: 'test'}

owner: "456123" }

i have this kind of array values object from my react formik app and i want to save it into the laravel backend database anybody tell me how to do this one using laravel 8 thanks.

CodePudding user response:

I suppose you have the table and have only columns named equipments and release_by other than id (which must be autogenerated) ,created_at and updated_at you can use table::insert($array) if you have other columns and they are nullable or you have to insert some other values you can use

$newData = new Table;
foreach ($array as $data) {
 $newData = new Table;
 $newData->equipments  => data['equipments'];
 $newData->release_by    => data['release_by'];
 $newData->save();
}

CodePudding user response:

If your json object like this format -

{
    owner:456123,
    holders: [
        { 
            equipments: 'test', 
            release_by: 'test'
        },
        { 
            equipments: 'test', 
            release_by: 'test'
        }
    ]
}

This process you can follow.

  1. Create a holder model. This holder model have relation with owner model.
  2. After creating the relationship, you need to create a controller for consume the request. This controller must have a FormRequest for validating your inputs.
  3. In this controller, you can insert your data using batch operation. How to bulk insert in laravel

I think it will help you for farther working process.

  • Related