How to insert all json file data in database? - laravel

I have JSON file and have data in it. I want to import all data in the database through DB seeders. I am getting an error Trying to get property name of non-object. I have multiple data how I can insert in the database?
public function run()
{
$json = File::get("public/kmz/WASASubdivisions.geojson");
$data = json_decode($json);
// dd($data);
foreach ($data as $obj){
Regions::create(array(
'name' => $obj[0]->Name,
'description' => $obj[0]->description,
'altitudeMode' => $obj[0]->altitudeMode,
'Town' => $obj[0]->Town,
'AC' => $obj[0]->AC,
'No_of_TW' => $obj[0]->No_of_TW,
'No' => $obj[0]->No,
'DC'=> $obj[0]->DC,
'HH_2017' => $obj[0]->HH_2017,
'FID' => $obj[0]->FID,
'Area_ha' => $obj[0]->Area_ha,
'Field_1' => $obj[0]->Field_1,
'Pop_Dens' => $obj[0]->Pop_Dens,
'Id' => $obj[0]->Id,
'Pop_2017' => $obj[0]->Pop_2017,
'Area_Sq'=> $obj[0]->Area_Sq,
));
}
}
Sample Json Format
31 => {#837
+"type": "Feature"
+"properties": {#838
+"Name": "Gujjar Pura"
+"description": null
+"altitudeMode": "clampToGround"
+"Town": "Shalimar Town"
+"AC": "31"
+"No_of_TW": "11"
+"No": "13"
+"DC": "38"
+"HH_2017": "30478"
+"FID": "31"
+"Area_ha": "648.327"
+"Field_1": "Gujjar Pura"
+"Pop_Dens": "54063.141167"
+"Id": "0"
+"Pop_2017": "196619"
+"Area_Sq": "3.63684"
}
+"geometry": {#839
+"type": "MultiPolygon"
+"coordinates": array:1 [
0 => array:1 [
0 => array:169 [ …169]
]
]
}
}

Let's support I have a model Post and I want to save additional data in JSON format in the posts table. In that case, we can use property $casts in Laravel. Which will cast our field value to whatever we gave.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
protected $table='posts';
protected $fillable = ['user_id', 'title', 'short_description', 'description', 'status', 'json_data'];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'json_data' => 'array',
];
}
Now we want to save data something like this
$data = [
'user_id' => 1,
'title' => 'abc',
'short_description' => 'test',
'description' => 'test',
'status' => true,
'json_data' => [
'additional_info' => '',
'post_image' => '',
...
],
];
$item = new Post;
$item->fill($data)->save();
This will save your json_data array values to JSON in the database. But when you will get data from the database it will convert that to array automatically.
For reference read this

since i am not a big fan of processing the json as a object
So the json_decode will accept the second arg so
$json = File::get("public/kmz/WASASubdivisions.geojson");
$data = json_decode($json,true);
dd($data);
foreach ($data as $obj)
{
Regions::create(array(
'name' => $obj['Name'],
'description' => $obj['description'],
'altitudeMode' => $obj['altitudeMode'],
'Town' => $obj['Town'],
'AC' => $obj['AC'],
'No_of_TW' => $obj['No_of_TW'],
'No' => $obj['No'],
'DC'=> $obj['DC'],
'HH_2017' => $obj['HH_2017'],
'FID' => $obj['FID'],
'Area_ha' => $obj['Area_ha'],
'Field_1' => $obj['Field_1'],
'Pop_Dens' => $obj['Pop_Dens'],
'Id' => $obj['Id'],
'Pop_2017' => $obj['Pop_2017'],
'Area_Sq'=> $obj['Area_Sq'],
));
}
Can You Post the dd() result and fileds sets of the table

public function run()
{
$json = File::get("public/kmz/WASASubdivisions.geojson");
$data = json_decode($json);
dd($data);
foreach ($data as $obj){
Regions::create(array(
'name' => $obj->Name,
'description' => $obj->description,
'altitudeMode' => $obj->altitudeMode,
'Town' => $obj->Town,
'AC' => $obj->AC,
'No_of_TW' => $obj->No_of_TW,
'No' => $obj->No,
'DC'=> $obj->DC,
'HH_2017' => $obj->HH_2017,
'FID' => $obj->FID,
'Area_ha' => $obj->Area_ha,
'Field_1' => $obj->Field_1,
'Pop_Dens' => $obj->Pop_Dens,
'Id' => $obj->Id,
'Pop_2017' => $obj->Pop_2017,
'Area_Sq'=> $obj->Area_Sq,
));
}
}

The attributes are under the properties key, but you're referencing them from the root of the object. e.g. $obj[0]->Name should be $obj[0]->properties->Name, etc.

Related

I cant get lastInsertId on laravel 7 project

$sql = DB::table('laravel_products')
->insert(array(
'name' => $name,
'price' => $price,
'qty' => $qty,
'description' => $description,
'uruu' => $uruu,
'garage' => $garage,
'duureg' => $duureg,
'tagt' => $tagt,
'talbai' => $talbai,
'haalga' => $haalga,
'tsonh' => $tsonh,
'shal' => $shal,
'tsonhtoo' => $ttsonh,
'hdawhar' => $bdawhar,
'lizing' => $lizing,
'utas' => $utas,
'email' => $email,
'hereg' => $hereg,
'bairshil' => $bairshil,
'bairlal' => $bairlal,
'ashig' => $ashigon,
'zahi' => $zahi,
'image' => $data
));
$lastInsertedID = $sql->lastInsertId();
When I try to insert its responses:
"Call to a member function lastInsertId() on bool"
I used insertGetId but its cant save multiple rows of pictures on mysql.
If you want to get the last inserted ID like that you can call that method on the PDO instance directly:
$id = DB::getPdo()->lastInsertId();
If the table has an auto-incrementing id, use the insertGetId method to insert a record and then retrieve the ID:
$id = DB::table('users')->insertGetId(
['email' => 'john#example.com', 'votes' => 0]
);
from : https://laravel.com/docs/5.8/queries#inserts
$data = new LaravelProducts(); //LaravelProducts is your Model Name
$data->name= $name; //here 'name' is your column name
$data->price= $price; //here 'price' is your column name
$data->qty= $qty; //here 'qty' is your column name
$data->description= $description; //here 'description' is your column name
..........
..........
$data->image= $image; //here 'image' is your column name
$data->save();
$lastInsertedId = $data->id;
You don't have to write a new query to collect last inserted id from database.
$laravel_product = DB::table('laravel_products')
->insertGetId( array(
'name' => $name,
'price' => $price,
'qty' => $qty,
'description' => $description,
'uruu' => $uruu,
'garage' => $garage,
'duureg' => $duureg,
'tagt' => $tagt,
'talbai' => $talbai,
'haalga' => $haalga,
'tsonh' => $tsonh,
'shal' => $shal,
'tsonhtoo' => $ttsonh,
'hdawhar' => $bdawhar,
'lizing' => $lizing,
'utas' => $utas,
'email' => $email,
'hereg' => $hereg,
'bairshil' => $bairshil,
'bairlal' => $bairlal,
'ashig' => $ashigon,
'zahi' => $zahi,
'image' => $data
)
);
foreach ($filenamesToSave as $filename) {
DB::insert('INSERT INTO laravel_products_images ( product_id, filename ) VALUES ( ?, ? )',[$laravel_product->id, $filename]);
return view('createproduct');
} // Foreach Closing
// Echo your inserted ID Like Below
echo $laravel_product->id;
It should be 100% working for you.

Problem loading data in repeatable without saving data in JSON format Laravel-Backpack

I'm using the repeatable, from Laravel-Backpack I can save the data into the two tables. However, I can not load these data when trying to edit a sale. It does not load the data in the form that were saved through the Repeatable.
Example:
When viewing the example of the demo through the link.
https://demo.backpackforelaravel.com/admin/dummy/create
It converts the data from the fields from the REPEATABLE to JSON, and saves in the database in a field called Extra.
Saved format in the extra field in the database:
{
"simple": "[{\"text\":\"TesteTesteTesteTeste\",\"email\":\"admin#admin\",\"textarea\":\"teste\",\"number\":\"1\",\"float\":\"1\",\"number_with_prefix\":\"1\",\"number_with_suffix\":\"0\",\"text_with_both_prefix_and_suffix\":\"1\",\"password\":\"123\",\"radio\":\"1\",\"checkbox\":\"1\",\"hidden\":\"6318\"}]",
}
In my case I am saving the data in different tables without using JSON.
//My Model
class Sales extends Model
protected $casts = [
'id' => 'integer',
'user_id' => 'integer',
'date_purchase' => 'date',
'client_id' => 'integer',
];
public function getProductsAttribute()
{
$objects = ItensProducts::where('product_id', $this->id)->get();
$array = [];
if (!empty($objects)) {
foreach ($objects as $itens) {
$obj = new stdClass();
$obj->product_id = "" . $itens->product_id;
$obj->quantity = "" . $itens->quantity;
$categoryProduct = CategoryProduct::where('product_id', $itens->product_id)->get();
$arrayCategoryProduct = [];
foreach ($categoryProduct as $stItens) {
$arrayCategoryProduct[] = $stItens->name;
}
$obj->categories_product = $arrayCategoryProduct;
$array[] = $obj;
}
}
//Converts JSON to the example of the extra database field
$array_result = json_encode(\json_encode($array), JSON_HEX_QUOT | JSON_HEX_APOS);
$array_result = str_replace(['\u0022', '\u0027'], ["\\\"", "\\'"], $array_result);
return $array_result;
}
My form:
//SalesCruController.php
protected function setupCreateOperation()
{
CRUD::addField([ // repeatable
'name' => 'products',
'label' => 'Produtos(s)',
'type' => 'repeatable',
'fields' => [
[
'name' => 'product_id', 'type' => 'select2', 'label' => 'Produtos',
'attribute' => "name",
'model' => "App\Models\Product",
'entity' => 'products',
'placeholder' => "Selecione o Produto",
'wrapper' => [
'class' => 'form-group col-md-6'
],
],
[
'name' => 'category_id', 'type' => 'select2', 'label' => "Categoria",
'attribute' => "name",
'model' => "App\Models\CategoryProduct",
'entity' => 'categories',
'placeholder' => "Selecione uma Categoria",
],
[
'name' => 'quantity',
'label' => "Quantidade",
'type' => 'text',
],
],
// optional
'new_item_label' => 'Adicionar',
'init_rows' => 1,
'min_rows' => 1,
'max_rows' => 3,
],);
}
}
Method Store
public function store()
{
$item = $this->crud->create($this->crud->getRequest()->except(['save_action', '_token', '_method']));
$products = json_decode($this->crud->getRequest()->input('products'));
$this->validateRepeatableFields($categoryProduct);
if (is_array($products)) {
foreach ($products as $itens) {
$obj = new ItensProduct();
$obj->sale_id = $item->getKey();
$obj->product_id = $itens->product_id;
$obj->quantity = $itens->quantity;
$obj->save();
$categoryProduct = json_decode($itens->categories);
foreach ($categoryProduct as $cItens) {
$objCat = new CategoryProduct();
$objCat->product_id = $obj->getKey();
$objCat->name = $cItens;
$objCat->save();
}
}
} else {
\Alert::add('warning', '<b>Preencha os campos de pelo menos um produto.</b>')->flash();
return redirect('admin/sales/create');
}
\Alert::success(trans('backpack::crud.insert_success'))->flash();
return redirect('admin/sales');
}
function validateRepeatableFields($categoryProduct)
{
foreach ($categoryProduct as $group) {
Validator::make((array)$group, [
'sale_id' => 'required',
'product_id' => 'required',
'quantity' => 'required',
], [
"product_id.required" => "O campo Produto é obrigatório",
"quantity.required" => "O campo quantidade é obrigatório",
])->validate();
}
}
I was able to solve the problem of returning the fields to the Repeatable form.
I want to share the solution if someone needs it. The error occurred when I tried to put the data from the category_id field which is a vector in a json it has to return like this, as shown below.
{"product_id": "4", quantity: "3", "category_id": "[10, 4, 8, 8]"}
The vector would have to be inside a string, I was passing the fields but was not converting the whole vector to a string in the format that the repeatable expected. Then I conceded the IDs in a string and in the end I conceded with the cohets and used the substring to remove the last virgulation, as the code below shows.
In this way I was able to return the fields with the appropriate information that were saved in the database in the Repeatable form.
public function getProductsAttribute()
{
$objects = ItensProducts::where('product_id', $this->id)->get();
$response = [];
if (!empty($objects)) {
foreach ($objects as $itens) {
$categoryProduct = CategoryProduct::where('product_id', $itens->product_id)->get();
$itensCatProd = '';
foreach ($categoryProduct as $itensCatProd) {
$itensCatProd .= $itensCatProd->id . ',';
};
$response[] = [
'product_id' => $itens->product_id,
'category_id' => '[' . substr($itensCatProd, 0, -1) . ']',
'quantity' => $itens->quantity,
];
return json_encode($response);
}
}
}

How can I do store multidimensional array base on name in Laravel collection?

In image you can see name and I want to store on base of name
Array index 0 & 2 have the same name. And I want to store same name in one array
Like This:
Josue Koepp DDS => {
id=>2,
item_name=>"Domenic Labadie"
},
{
id=>0,
item_name=>"Prof. Jakayla Willms"
}
}
You can use groupBy()
$collection = collect([
['account_id' => 'account-x10', 'product' => 'Chair'],
['account_id' => 'account-x10', 'product' => 'Bookcase'],
['account_id' => 'account-x11', 'product' => 'Desk'],
]);
$grouped = $collection->groupBy('account_id');
$grouped->toArray();
/*
[
'account-x10' => [
['account_id' => 'account-x10', 'product' => 'Chair'],
['account_id' => 'account-x10', 'product' => 'Bookcase'],
],
'account-x11' => [
['account_id' => 'account-x11', 'product' => 'Desk'],
],
]
*/
In your case:
$lists = $lists->groupBy('name')->toArray();

Using isDirty in Laravel

I'm using the isDirty() method in my controller to check if any field is changed. Then I am saving the old data of a field and the new data in a table. The code is working fine; however, how can I optimize this code?
By using the below code, I will have to write each field name again and again. If request->all() has 20 fields, but I want to check six fields if they are modified, how can I pass only 6 fields in the below code, without repeating?
Controller
if ($teacher->isDirty('field1')) {
$new_data = $teacher->field1;
$old_data = $teacher->getOriginal('field1');
DB::table('teacher_logs')->insert(
[
'user_id' => $user->id,
'teacher_id' => $teacher->id,
'old_value' => $old_data,
'new_value' => $new_data,
'column_changed' => "First Name",
]);
}
You can set a list of what fields you want to be checking for then you can loop through the dirty fields and build your insert records.
use Illuminate\Support\Arr;
...
$fields = [
'field1' => 'First Name',
'field2' => '...',
...
];
$dirtied = Arr::only($teacher->getDirty(), array_keys($fields));
$inserts = [];
foreach ($dirtied as $key => $value) {
$inserts[] = [
'user_id' => $user->id,
'teacher_id' => $teacher->id,
'old_value' => $teacher->getOriginal($key),
'new_value' => $value,
'column_changed' => $fields[$key];
];
}
DB::table(...)->insert($inserts);
i tried following code after getting idea by lagbox in comments, and i have found solution to my problem.
$dirty = $teacher->getDirty('field1','field2','field3');
foreach ($dirty as $field => $newdata)
{
$olddata = $teacher->getOriginal($field);
if ($olddata != $newdata)
{
DB::table('teacher_logs')->insert(
['user_id' => $user->id,
'teacher_id' => $teacher->id,
'old_value' => $olddata,
'new_value' => $newdata,
'column_changed' => "changed",
]);
}
}

Result by model

I have this query:
$data = TableRegistry::get('Dogs');
$data = $data->find('all')
->contain(['Foods'])
->select(['name','breed','sex','Foods.name','Foods.quality'])
->last()
->toArray();
It returns this result:
[
'name' => 'Dug',
'breed' => 'Golden Retriever',
'sex' => 'Male',
'food' => [
'name' => 'Best Food',
'quality' => 'A+'
]
]
I want to know if there is any way to make CakePHP return the result as:
[
'dog' => [
'name' => 'Dug',
'breed' => 'Golden Retriever',
'sex' => 'Male'
],
'food' => [
'name' => 'Best Food',
'quality' => 'A+'
]
]
How would I do this? I am pretty sure it's very simple, but I can't figure it out.
Maybe like this:
$data => [
'dog' => [
'name' => $dog->name,
'breed' => $dog->breed,
'sex' => $dog->sex
],
'food' => $dog->foods
];
$this->set('data', $data);
So following Salines' post, I decided to just build something quick and easy to work with since the content is a bit more dynamic than the example I posted.
$data = TableRegistry::get($this->table);
$data = $data->find()
->contain($associated)
->select($this->data_fields)
->last()
->toArray();
$main = strtolower(Inflector::singularize($this->table));
$data[$main] = [];
foreach ($data as $key => $value) {
if(!is_array($value)) {
$data[$main][$key] = $value;
unset($data[$key]);
}
}

Resources