when I update some columns of the table it insert new field in table
"id": 1,
"invoice_id": "0001-2019-20",
"client_id": "1",
"currency_id": "4",
"date": "2019-06-06",
"subject": "wordpress",
"total": "3000"
when i update only subject and total it will insert new field
"id": 2,
"invoice_id": "",
"client_id": "0",
"currency_id": "0",
"date": "0000-00-00",
"subject": "OMS",
"total": "0"
here is my controller,
$invoices = new Invoice;
$invoices->client_id = $request->get('client_id');
$invoices->currency_id = $request->get('currency_id');;
$invoices->subject = $request->get('subject');
$invoices->save();
The code you are using is for creating a new record.
However you are almost there.
So let's say you want to update below data
{"id": 1,
"invoice_id": "0001-2019-20",
"client_id": "1",
"currency_id": "4",
"date": "2019-06-06",
"subject": "wordpress",
"total": "3000"}
Use Below Code to update that row.
$invoices = Invoice::find($request->get('id'));
$invoices->client_id = $request->get('client_id');
$invoices->currency_id = $request->get('currency_id');
$invoices->subject = $request->get('subject');
$invoices->save();
There are alternative method as below.
$invoices = Invoice::find($request->get('id'));
$invoices->update([
'client_id' => $request->get('client_id'),
'currency_id' => $request->get('currency_id'),
'subject' => $request->get('subject')
]);
Note: For above method array key names and your table column names
must be same.
Related
I want to add variable to each object of collection inside collection. Here JSON response like this:
{
"id": 16,
"survey_id": "8",
"title": "How are you?",
"created_at": "2020-02-06 04:21:44",
"updated_at": "2020-02-06 04:21:44",
"answers": [
Here I want to add variable to each answer
{
"id": 52,
"question_id": "16",
"text": "VERY GOOD",
"created_at": "2020-02-06 04:21:44",
"updated_at": "2020-02-06 04:21:44",
"reports_count": "4",
"responded": 2
},
{
"id": 53,
"question_id": "16",
"text": "OK",
"created_at": "2020-02-06 04:21:44",
"updated_at": "2020-02-06 04:21:44",
"reports_count": "4",
"responded": 2
},
{
"id": 54,
"question_id": "16",
"text": "BAD",
"created_at": "2020-02-06 04:21:44",
"updated_at": "2020-02-06 04:21:44",
"reports_count": "2",
"responded": 2
}
]
},
Overall, I want to add for every answers variable like $respond = $answer->reports()->count(); Help PLease!!
You could do something like this, if you want to calculate it in the collection directly.
$yourCollection->transform(function($collectionItem) {
$collectionItem['responded'] = $collectionItem->answers->count();
return $collectionItem;
});
But you could do this also on the sql side. I think it should be also the better way ;)
I would fetch the answers from the database before assigning that array to a new question-object-property.
public function get() {
// fetch parent question
$question = Question::where('title', $title)->get();
// fetch answers
$answers = Answers::where('parent_id', $question->id)->get();
// create property called "answers"
$question->answers = $answers;
return response()->json($question);
}
I have 2 tables Customer(Parent) and jobCode(Child) with one to many relationships
I want to retrieve a child record but with one extra field from the parent (customerGuid) as well. My code:
$jobCodes=JobCode::all();
foreach ($jobCodes as $jobCode) {
$jobCode['customerGuid']=$jobCode->customer->guid;
// I also tried $jobCode->setAttribute('customerGuid',$jobCode->customer->guid);
}
return $jobCodes;
I was expecting just the parent's guid field to be appended to each jobCode object and returned. However the ENTIRE customer parent object is returned!
[{
"id": 137,
"customerId": 1,
"jobCode": "Journeyman Plumber",
"jobDescription": "Journeyman Plumber",
"created_at": null,
"updated_at": "2017-01-27 12:20:27",
"guid": "28f35e94-e483-11e6-98e9-e0db55883624",
"customerGuid": "8d48931d-dc61-11e6-8927-e0db55883624",
"customer": {
"id": 1,
"name": "ACME",
"address1": "",
"address2": "",
"city": "San Jose",
"zip": "",
"phone": "",
"fax": "",
"email": "",
"guid": "8d48931d-dc61-11e6-8927-e0db55883624",
"stateName": "California",
"created_at": null,
"updated_at": "2017-01-20 07:10:59"
}
}, {
"id": 138,
"customerId": 1,
"jobCode": "JRP PreFab",
"jobDescription": "JRP",
......,
Its because your return statement returns $jobCodes; which is the entire table you retrieve here: $jobCodes=JobCode::all();
try putting this inside your loop
echo '$jobCode' to see what is the output every time it loops
Reaching for the relationship customer on $jobCode you automatically lazy load the relationship object, which is stored in $jobCode->customer attribute.
Try this instead just returning the collection:
// return $jobCodes;
return $jobCodes->map(function($jobCode){
$jobCode = $jobCode->toArray();
unset($jobCode['customer']);
return $jobCode;
});
I have the following code:
$orders = OrderProduct::where(function ($query) use ($request) {
})->with('order_products')->orderBy('status', 'desc')->paginate(50)->toArray();
And order_products function is:
public function order_products()
{
return $this->hasMany("App\Order", "order_id", "order_id");
}
It gives me output result:
{
"user_id": "1",
"created_at": "2016-12-18 14:06:11",
"status": "2",
"note": "34535345",
"order_id": "2",
"address": "Kiev",
"courier_id": null,
"payment_type": "0",
"order_products": [
{
"id": 73,
"product_id": "1265",
"amount": "1"
},
{
"id": 74,
"product_id": "1266",
"amount": "1"
}
]
I need to join order_products with products_details, that to give title of product for each order like as:
"order_products": [
{
"id": 73,
"product_id": "1265",
"amount": "1",
"title": "Product name"
},
{
"id": 74,
"product_id": "1266",
"amount": "1",
"title": "Product name"
}
]
Instead this I get a new model output in response:
"products_details": [
{}, {}
]
How can I join two with models?
without joining, just using your first code:
in order_products, override the toArray() method.
function toArray() {
return [
id => $this->id,
product_id => $this->product_id,
amount => $this->amount,
title => $this->details->name
];
}
wich $this->details->name is the relation between order_products and products_details
I'm returning JSON from LengthAwarePaginator but the JSON's data property is not an array. I need it to be an array. Any ideas?
// grab query parameters
$pageNumber = $request->input('page');
$pageSize = $request->input('pageSize');
// if query params do not exist call with defaults
if(!$pageNumber) {
$pageNumber = 1;
}
if(!$pageSize) {
$pageSize = 5;
}
$offset = ($pageNumber * $pageSize) - $pageSize;
// slice full array data based on page number and page size
$itemsForCurrentPage = array_slice($arrayOfData, $offset, $pageSize, true);
return new LengthAwarePaginator($itemsForCurrentPage, count($this->orgUsers), $pageSize, $pageNumber);
Returned data:
{
"total": 30,
"per_page": 5,
"current_page": 2,
"last_page": 6,
"next_page_url": "/?page=3",
"prev_page_url": "/?page=1",
"from": 6,
"to": 10,
"data": {
"5": {
"userId": "564110eadcb39832268ea873",
"email": "dsdfgdfg#il.com",
"isActive": true,
"firstName": "dsdfgdfg",
"lastName": "dsdfgdfg",
"permissionType": "dsdfgdfg"
},
"6": {
"userId": "564110ea2169bc358a3b65c2",
"email": "dsdfgdfg#d.com",
"isActive": false,
"firstName": "dsdfgdfg",
"lastName": "dsdfgdfg",
"permissionType": "dsdfgdfg"
},
"7": {
"userId": "564110eaee662f30c4bd6772",
"email": "dsdfgdfg#dsdfgdfg.com",
"isActive": true,
"firstName": "dsdfgdfg",
"lastName": "dsdfgdfg",
"permissionType": "dsdfgdfg"
},
"8": {
"userId": "dsdfgdfg",
"email": "dsdfgdfg#dsdfgdfg.com",
"isActive": true,
"firstName": "dsdfgdfg",
"lastName": "dsdfgdfg"
},
"9": {
"userId": "564110eaf9526eb5ddd673a4",
"email": "dsdfgdfg#dsdfgdfg.com",
"isActive": true,
"firstName": "dsdfgdfg",
"lastName": "dsdfgdfg"
}
}
}
TIA
The problem is that the ids remain the keys of your array when array_slice-ing. But since some keys are missing, especially 0, 1, 2, … the array is henceforth treated as associative (['key1'=>'value1', 'key2'=>'value2', …]) rather than numerically indexed (['value1', 'value2', …]) when encoding to json.
The solution is to succeed your array_slice(…) with an array_values() call.
return new LengthAwarePaginator(array_values($itemsForCurrentPage), count($this->orgUsers), $pageSize, $pageNumber);
Edit: In case your $arrayOfData is an Eloquent/Illuminate Collection, you can use the methods ->slice($offset, $pageSize)->values() on it. Looks nicer!
I have three tables:
users
id
name
role_id
password
...
role_user
id
role_id
user_id
roles
id
name
slug
...
Now I want to get a user list with users.id,users.name,
roles.id. That's my code:
$query = User::with(['roles'=>function($q){
$q->lists('role_id');
}])->get(['id','name']);
the response like that
{
"id": "1",
"name": "aaaa",
"roles": []
},
{
"id": "2",
"name": "bbbb",
"roles": []
},
when i don't pass the array to get method,the response like that:
{
"id": 1,
"name": "aaaa",
"password": "xxxxxxx",
"created_at": "2015-05-07 14:15:00",
"roles": [
{
"role_id": 2,
"pivot": {
"user_id": 1,
"role_id": 2
}
}
]
},
{
"id": 2,
"name": "bbbb",
"password": "xxxxxxx",
"created_at": "2015-05-05 14:15:00",
"roles": [
{
"role_id": 2,
"pivot": {
"user_id": 2,
"role_id": 2
}
}
]
},
But i do not want the password,created_at and pivot field. How to filter these?
To get relations you need to get the foreign keys. Try this
$query = User::with(['roles'=>function($q){
$q->get(['id', 'name', 'slug']);
}])->get(['id','name', 'role_id']);
As for the pivot table, can you post you roles relation in the user model?
Edit
Add this to your user model to hide the pivot properties
protected $hidden = ['pivot'];
You can add more fields to that property to remove them from all queries.