How to save a JSON Object to MySQL Database in laravel

I’m sending data with a ajax call to my laravel server at http://127.0.0.1:8000/data

Laravel Route

Route::post('/data',[MainController::class, 'data']);

my modle
 public function up()
{
    Schema::create('names', function (Blueprint $table) {
        $table->id();
        $table->string('name');
        $table->timestamps();
    });
}

Controller
   function data(Request $request)
{

$requestPayload = file_get_contents("php://input");
$object = json_decode($requestPayload);
return ($object);

}

Json data i want to save in database
[
{
“name”: “Monika khrolia”
},
{
“name”: “Ranjana”
},
{
“name”: “Ramesh Kumar”
},
{
“name”: “Ansuman Biswas”
},
{
“name”: “Avijit Ghosh”
},
{
“name”: “RAHUL.R”
},
{
“name”: “ITI Shitoley”
},
{
“name”: “Shubham soni”
},
{
“name”: “Awanish Ranjan Rai”
},
{
“name”: “Neetu Sharma”
},
{
“name”: “Rishi Raj”
},
{
“name”: “Priyanka Pokharkar”
},
{
“name”: “Chetan Mistry”
},
{
“name”: “Chiman Mandali”
},
{
“name”: “Raka Yadav”
},
{
“name”: “Munna Kumar”
},
{
“name”: “kayum ansari”
},
{
“name”: “Meraj Ahmad Naqui”
},
{
“name”: “Hem Kumar Sharma”
},
{
“name”: “Shantangsu Kumar Das”
},
{
“name”: “Sreenivasreddy”
},
{
“name”: “Mahendra Kumar”
},
{
“name”: “Pragya Singhal”
},
{
“name”: “Khushboo Talwar”
},
{
“name”: “Milan Gayen”
},
{
“name”: “Ankita Pandey”
},
{
“name”: “Nooruddin Saheb”
},
{
“name”: “S.JAHIR HUSSAIN”
},
{
“name”: “Arunraj Tamilselvam Harijan”
},
{
“name”: “Kunal Murlidhar Kamble”
},
{
“name”: “ADYASHA BEJ”
},
{
“name”: “Rajendra Yuvraj More”
},
{
“name”: “sunil”
},
{
“name”: “Sudipta Dey”
},
{
“name”: “raman prakash”
},
{
“name”: “Harender”
},
{
“name”: “Sk Tambirul Islam”
},
{
“name”: “Ravi yadav”
},
{
“name”: “Maneesh Singh”
},
{
“name”: “Navneet Chauhan”
}
]

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You have several options to deal with this (documentation):

  • You can do a bulk insert

DB::table( 'names' )->insert( object );

or
DB::table( 'names' )->insertOrIgnore( object );
  • Or you can do the save it using the model (in case you want to validate o whatever) (documentation):

foreach( $objectList as $objectItem ) 
{
    $name = Name::firstOrNew( [ 'name' => $objectItem->name ]);
    $name->save();
}

Best,


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x