Megandi Megandi - 6 months ago 48
JSON Question

Input JSON type data to Laravel 5.2

I have file txt (data.txt) with this value :

{"id":"1","title":"first Testing","completed":"Yes"}

{"id":"2","title":"Second Testing","completed":"no"}

{"id":"3","title":"Third Testing","completed":"no"}


and table Data with field
id
,
title
, and
completed
..

how I can input all value in data.txt into my Table (Data) with laravel 5.2??

Thanks before.. and sorry for my bad english..

Answer

Read file and convert it to PHP Array

 $arrays = json_decode(file_get_contents('data.txt'), true);

Then with simple foreach

foreach($arrays as $array) {
   $myObject = new Model();
   $myObject->id = $array['id'];
   $myObject->title = $array['title'];
   $myObject->completed = $array['completed'];
   $myObject->save();
}

Or you could do it straightfoward if you defined $fillable attributes

foreach($arrays as $array)
   Model::create($array);

Eloquent: Mass Assignment

Using Query Builder

DB::table('data')->insert($arrays);

Query Builder: Insert