Formatting Array saved in database to blade view in laravel - arrays

I have a DB table which stores id, cart(array), updated_at, created_at. How can I deconstruct the array and display the items in the view as list items.
3
{"3":{"name":"iPhone","quantity":2,"price":"500.00"},"4":
{"name":"Samsung","quantity":1,"price":"344.00"}}
2019-11-10 07:50:53
______________________
ProductsController
______________________
public function cartsIndex(Request $request)
{
$carts = Cart::all();
$carts = json_decode($carts);
// return view('cartsIndex')->with(['carts' => $carts]);
dd($carts);
}
I want the cart to be displayed as below.
ID - 3
Name: Iphone
Quantity: 2
Price: 500
Name: Samsung
Quantity: 1
Price: 344

use laravel's $cast attribute in your model. It will automatically help you to convert your data to json while storing in database and will help you access them as array when you retrieve them.
protected $cast = [
'cart' => 'array' // name of the column you want to store as json and retrieve as array
];
for reference https://laravel.com/docs/6.x/eloquent-mutators#array-and-json-casting

Related

how to make an laravel 8 API for saving an array of objects

{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.
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.
Create a holder model. This holder model have relation with owner model.
After creating the relationship, you need to create a controller for consume the request. This controller must have a FormRequest for validating your inputs.
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.
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();
}

how to count the same array value from database in laravel?

I use Laravel.
I saved the array to the database in the form of a string like this.
enter image description here
Then I want to summarize each piece of data the same. for example "Web Dev" is 5, "Android Dev" is 3.
how to do this? I have used "Has" but the method is undefined.
$summary = [
'byGender' => [
'male' => Member::whereGender('MALE')->count(),
'female'=> Member::whereGender('FEMALE')->count()
],
'bySkill' => [
'WebDev' => Member::expertiseCategoryHas(["Web Dev"])->count(),
'AndroidDev' => Member::expertiseCategoryHas(["Android Dev"])->count(),
'BackendDev' => Member::expertiseCategoryHas(["Backend Dev"])->count()
]
];
I suggest you to save your data to JSON value. Then you can use whereJsonContains() to get desired result.
First, to auto convert your array to json you can do this on your Model:
Model.php
public function setExpertiseCategoriesAttribute($value)
{
$this->attribute['expertise_categories'] = json_encode($value);
}
Then on Controller use whereJsonContains(), for example to count Web Dev:
Model::whereJsonContains('expertise_categories', 'Web Dev')->count();

Search for a particular field in a array object and put it in another array for displaying a table in angular

I am new to angular I am getting an object array as a response from the server I need to search if any of the arrays have same key value and then put the corresponding array element values in another array for displaying it in a table.
My scenario I am passing Inquiry Number as my input Eg: 10002
My Inquiry response contains the following details Inquirydocumentno, inquirydate, materialno, name of materialinquired etc..,
My actual Response is
[
{
InquiryDate: ["2015-03-04"]
InquiryType:["A"]
MaterialNo: ["30"]
Material Name: ["Chair"]
InquiryDocument No: ["0010000012"]
},
{
InquiryDate: ["2019-03-04"]
InquiryType:["A"]
MaterialNo: ["31"]
Material Name: ["Book"]
InquiryDocument No: ["0010000015"]
},
{
InquiryDate: ["2019-03-04"]
InquiryType:["A"]
MaterialNo: ["31"]
Material Name: ["Bag"]
InquiryDocument No: ["0010000015"]
},
{
InquiryDate: ["2015-05-19"]
InquiryType:["A"]
MaterialNo: ["34"]
Material Name: ["lamp"]
InquiryDocument No: ["0010000018"]
}
]
Here In this response the details such as Inquiry date and inquiry documentno, inquiry type are fixed as header details and need to be displayed as header table whereas material no and material name are item details need to be displayed in another table on click the corresponding inquirydocument no it should display all related item details for it.
Eg: InquiryDocumentNo: 0010000015 appears two times in the response I need to be displayed it as one time in header table and on clicking a buuton details it should display the 2 item(Bag, Book) inquired in another table.
I am trying to check if the documentno is same in the response array and trying to push the corresponding item details in another array in my code(appcomponent.ts) but it is doing correctly can anyone help me to figure it out and how to do this
inq =[];
for(var i=0;i<array.length;i++)
{
var element=array[i];
for(var j=i+1;j<array.length;j++)
{
var elt =array[j];
if(element.inquirydocno==elt.inquirydocno)
{
this.inq.push(elt.Materialno);
this.inq.push(elt.Materialname);
}
}
}
console.log(this.inq);
I had attached an image of how my output should be displayed
I'd recommend to use a dictionary for the 'details table'.
Something like this
export interface InquiryItem {
materialNo: string[];
materialName: string[];
}
inquiryItems: { [inquiryDocumentNo: string]: InquiryItem[] } = {};
// Manual populating
inquiryItems['001'] = [];
inquiryItems['002'] = [];
inquiryItems['001'].push({materialNo: '31', materialName: 'Book'});
inquiryItems["001"].push({materialNo: '31', materialName: 'Bag'});
inquiryItems["002"].push({materialNo: '30', materialName: 'Chair'});
// From response array
responseArray.forEach(entry => {
const docNo = entry.InquiryDocumentNo;
if(inquiryItems[docNo] === undefined)
inquiryITems[docNo] = [];
inquiryItems[docNo].push({
materialNo: entry.Materialno;
materialName: entry.Materialname;
});
})
// Retrieval:
docItems: InquiryItem[] = inquiryItems['0010000015'];

How to set value for additional column in pivot table in OctoberCMS?

I have doctor and specialization table, and have doctor_specialization_pivot table. In my pivot table I have the following columns:
| doctor_id | additional_data | specialization_id |
additional_data is from the doctor model along with the doctor_id.
In my doctor model file, I have this relationship:
public $belongsToMany = [
'specialization' => [
'path\to\specialization\model',
'table' => 'doctor_specialization_pivot',
'parentKey' => 'doctor_id',
'otherKey' => 'specialization_id',
]
];
Now during submit of form, I'm getting this error:
SQLSTATE[HY000]: General error: 1364 Field 'additional_data' doesn't have a default value (SQL: insert into doctor_specialization_pivot (doctor_id, specializations_id) values (1, 3))"
I tried adding to my relationship 'pivot' => ['additional_data']. But still getting the same error.
I checked the submitted data and additional_data is not empty. I checked from OctoberCMS forums but not getting straight forward answers such as this and this.
Okay. I found the answer to my own question.
I'll answer in detail to help everyone. After digging and blind shooting. According to this documentation here, we can use the method attach() to attach a role to a user by inserting a record in the intermediate table that joins the models.
What confuse me in the documentation is that it uses a $roleId variable and I didn't understand where the $roleId came from. If it's the id of the parent table or the id of other table.
Sample from the link:
$user = User::find(1);
$user->roles()->attach($roleId);
So what I did in my doctor model, I hook to the event beforeSave, use the relationship ($this->specialization) as the first parameter instead of the id in the docs. The $this->specialization() is the relationship too defined in belongsToMany.
Answer:
public function beforeSave()
{
$this->specialization()->attach($this->specialization,['additional_data' => 'additional data from doctor table']);
}
The implementation is pretty much like this video from Watch Learn (Ivan). You can learn a lot about OctoberCMS just by watching his guide on it. Here is the documentation on it as well. This is the example info that I have done.
WARNING Another known flaw is you can't apply this to a model record that isn't created yet. Unlike the standard relation widget which waits until it is saved before attaching records this attaches records in a separate overlay form.
Here is my model.php relationship:
public $belongsToMany = [
'equipments' => [
'Brandon\Pixelrpg\Models\Equipments',
'table' => 'brandon_pixelrpg_equipment_inventory',
'key' => 'inventory',
'otherKey' => 'equipment',
'pivot' => ['quantity']
]
];
Here is my controller.php:
public $implement = [
'Backend\Behaviors\ListController',
'Backend\Behaviors\FormController',
'Backend\Behaviors\ReorderController',
'Backend\Behaviors\RelationController'
];
public $listConfig = 'config_list.yaml';
public $formConfig = 'config_form.yaml';
public $reorderConfig = 'config_reorder.yaml';
public $relationConfig = 'config_relation.yaml';
Here is my config_relation.yaml:
equipments:
label: Equipments
view:
list:
columns:
id:
label: ID
type: number
searchable: true
sortable: true
name:
label: Name
type: text
searchable: true
sortable: true
value:
label: Value
type: number
searchable: true
sortable: true
updated_at:
label: Updated
type: datetime
searchable: true
sortable: true
pivot[quantity]:
label: Quantity
type: number
pivot:
form:
fields:
pivot[quantity]:
label: Quantity
type: number
default: 0
I am just going to make a new answer and assume is what you need because you have yet to show any code on how your form works. This is how I would update the pivot information from a frontend form.
Relationship in model.php:
public $belongsToMany = [
'specialization' => [
'path\to\specialization\model',
'table' => 'doctor_specialization_pivot',
'parentKey' => 'doctor_id',
'otherKey' => 'specialization_id',
'pivot' => ['additional_data'] //This is required
]
];
Then in some php code lets call it onAddSpecialization():
public function onAddSpecialization() {
//Calling a function to get the doctor id maybe from the signed in user
$doctor = Doctors::find($this->$doctorId());
//We get our Specialization from an input
$specialization = Specialization::find(Input::get('specialization_id'));
//We get our additional data from an input
$additional_data = Input::get('additional_data');
//Now we are going to attach the information
$doctor->specialization()->attach($specialization, ['additional_data' => $additional_data]);
}
Now an example of updating our additional data:
public function onUpdateAdditionalData() {
//Calling a function to get the doctor id maybe from the signed in user
$doctor = Doctors::find($this->$doctorId());
//If you get specialization by id from an input. I believe you need to go through the relationship in order to access the correct pivot information.
$specialization = $doctor->specialization->where('id', Input::get('specialization_id'))->first();
//Insert the new pivot information
$specialization->pivot->additional_data = $new_additional_data;
//Save
$specialization->pivot->save();
}

Understanding how backbone collection fetch and model fetch work

So, when i try to send a collection from server with duplicate entry (same id) backbone doesn't render that element.
But on model.fetch() if i return a model with an already existing id, it works.So now we have a collection with same ids.
Why is this different behaviour, i was thinking backbone will verify(check if that id alread exist) the incoming model before updating it and not render it.
EDIT
on collection.fetch i get this
var coll = [{name: 'foo', id: 1 }, {'name': 'bar', id: 2 }] // just representation;
now i do model.fetch() for second model, and the server responds this
{'name': 'new bar', 'id': 1} // no-error the view gets updated

Resources