Laravel access JSON object in controller - laravel

I have this array in the controller after the submitted form holds in variable $product.
[
{
"id": 2,
"name": "nancy",
"cost": 34,
"quantity": 0,
"barcode": 12345,
"category_id": 2,
"created_at": "2020-07-05T16:04:10.000000Z",
"updated_at": "2020-07-09T04:06:09.000000Z"
},
{
"id": 5,
"name": "jk",
"cost": 100,
"quantity": 2,
"barcode": 147258,
"category_id": 2,
"created_at": "2020-07-08T20:34:56.000000Z",
"updated_at": "2020-10-18T13:09:16.000000Z"
}
]
How can I access the properties in objects like id, name, barcode ?

If you want to make it as array of array.
$products = json_decode($products, true); // Return array of array.
foreach($products as $product){
echo $product['name'];
}

Just decode it, use json_decode
$products = json_decode($products, true); // When TRUE, JSON objects will be returned as associative arrays
foreach($products as $product){
echo $product['id'];
}

Related

Filter Data with Pivot Table Laravel Eloquent

I want to filter users based on their subscription_status which s stored in a pivot table.
I have Three tables users , subscription_packages , subscription_package_user
$user=User::with(['studentDetails','subscriptionsSatus.courses'])
->withPagination($offset,$perPage)
->get()
->sortBy('first_name')->values();
this code return the response is
[
{
"id": 44,
"first_name": "Abcd Test",
"last_name": "Test lastname",
"student_details": null,
"subscriptions_satus": [
{
"id": 1,
"name": "Gold",
"price": 3000,
"user_id": "2"
"pivot": {
"user_id": 44,
"subscription_package_id": 1,
"subscription_status": "on_free_trial",
"expires_on": null,
"id": 9
},
"courses": [
{
"id": 18,
"title": "English Grammar for Class 3",
"price": 400,
"strikethrough_price": null,
"status": "draft",
"user_id": 2,
"image": "http://127.0.0.1:8000/courses/1615702915.png",
"description": null,
"pivot": {
"subscription_package_id": 1,
"course_id": 18,
}
}
]
}
]
}]
i want to return only users who having subscription_status =$filter.
$filter='acive'or 'on_free_trail'
my model is
public function subscriptionsSatus()
{
return $this->belongsToMany(SubscriptionPackage::class)->withTimestamps()->withPivot('subscription_status','expires_on','id');
}
I havetried
$filter=$request->input('filter')??"active";
$user=User::with(['studentDetails','subscriptionsStatus.courses'])
->whereHas('subscriptionsStatus', function($query) use($filter){
$query->wherePivot('subscription_status','=',$filter);
})
->withPagination($offset,$perPage)
->get()
->sortBy('first_name')->values();
But Got error Column not found 'pivot'
You need to use wherePivot along with the orWhere like below:
public function subscriptionsStatus()
{
return $this->belongsToMany(SubscriptionPackage::class)
->withTimestamps()
->withPivot('subscription_status','expires_on','id')
->wherePivot(function($q){
return $q->where('subscription_status','=','active')
->orWhere('subscription_status','=','on_free_trail');
});
}
Update
Or in your controller:
$user=User::with(['studentDetails','subscriptionsStatus.courses'])
->whereHas('subscriptionsStatus', function($query) use($filter){
$query->withPivot('subscription_status')
->wherePivot('subscription_status','=',$filter);
})
->withPagination($offset,$perPage)
->get()
->sortBy('first_name')->values();

Laravel filter with where statement

I have this code in my controller and the output is this
$list = ShopDepartment::with('shop','grocery', 'dailylist')->get();
return $list;
Output example for the first item is this
{
"id": 2,
"shop_id": 1,
"name": "Grønt",
"order": "2",
"created_at": "2020-10-12 14:03:57",
"updated_at": "2020-10-12 14:03:57",
"shop": {
"id": 1,
"name": "Netto",
"address": null,
"type": null,
"created_at": "2020-10-12 14:04:35",
"updated_at": "2020-10-12 14:04:35"
},
"grocery": [],
"dailylist": []
},
But if I want to filter the output for shop.id it wont allow me. Any idea how to do this? I assume I can not filter it like that...
$list = ShopDepartment::with('shop','grocery', 'dailylist')->where('shop.id', 1)->get();
return $list;
You could try something like this:
$list = ShopDepartment::with(['shop' => function($query) {
$query->where('id', 1);
}, 'grocery', 'dialylist'])->get();

Laravel get only one column from relation

I have a table user_childrens whose contains id_parent and id_user.
I'm trying to list all childrens of the parent with this:
code:
//relation in model via belongsTo
$idparent = auth('api')->user()->id;
$list = UserChildren::where('id_parent',$idparent)
->with('child:id,name,email')
->get();
return $list->toJson();
The return is:
[
{
"id": 1,
"id_parent": 1,
"id_user": 1,
"created_at": null,
"updated_at": null,
"child": {
"id": 1,
"name": "Mr. Davin Conroy Sr.",
"email": "prempel#example.com"
}
},
{
"id": 4,
"id_parent": 1,
"id_user": 2,
"created_at": null,
"updated_at": null,
"child": {
"id": 2,
"name": "Krystel Lehner",
"email": "cernser#example.net"
}
}
]
But it's API so I want only the child column like:
[
{
"id": 1,
"name": "Mr. Davin Conroy Sr.",
"email": "prempel#example.com"
},
{..}
]
UserChildren Model:
public function child() {
return $this->belongsTo('App\User','id_user','id');
}
I know that I could do this via .map() on collection but maybe there is other solution already on this query
You can use this code
$idparent = auth('api')->user()->id;
$childs = User::whereHas('user_childrens', function ($query) use ($idparent) {
$query->where('id_parent', $idparent);
})->get(['id', 'name', 'email']);
dd($childs->toJson());
And User model define user_childrens relation.
public function user_childrens()
{
return $this->hasMany('App\UserChildren','id_user','id');
}
See also docs https://laravel.com/docs/5.5/eloquent-relationships#querying-relationship-existence

Laravel - way to sum total_balance of all children.balance columns with just one request?

I need to simplify my data structuring. I want to get sum of balances in children accounts of a parent account. Here is how my object is structured:
Account Types
Children Types
Account 1 ( has balance of 9000 )
Account 2 ( has balance of 5000 )
I want to get total balance of all children accounts:
Account Types
Children Types - total_balance = 14000
How to do this without looping through the object, but using only the query builder of Laravel?
This is the request in my controller:
$user = \Auth::user()->id;
$accounts = AccountType::where('parent_id', 0)
->where('virtual', '=', 0)
->with(['children', 'children.accounts' => function ($query) use ($user) {
$query->where('user_id', '=', $user);
}])
->get();
return $accounts;
And this is the object that I get:
{
"id": 1,
"name": "Savings",
"parent_id": 0,
"virtual": 0,
"created_at": "2016-10-27 10:28:59",
"updated_at": "2016-10-27 10:28:59",
"children": [
{
"id": 2,
"name": "General Savings",
"parent_id": 1,
"virtual": 0,
"created_at": "2016-10-27 10:28:59",
"updated_at": "2016-10-27 10:28:59",
"accounts": [
{
"id": 25,
"institution_id": 0,
"balance": 9000,
"account_nickname": "Money Laundering",
"is_primary": 1,
"account_type_id": 2,
"user_id": 2,
"created_at": "2016-10-31 16:47:23",
"updated_at": "2016-10-31 16:47:23"
},
{
"id": 26,
"institution_id": 0,
"balance": 5000,
"account_nickname": "Moneymarket Savings",
"is_primary": 0,
"account_type_id": 2,
"user_id": 2,
"created_at": "2016-10-31 16:48:30",
"updated_at": "2016-10-31 16:48:30"
}
]
}
]
Is there a way to do that?
This should give you a list of all account types a user has containing a the total_balance of all accounts under each account_type:
$userAccountTypes = DB::table('account_types AS at')
->select(DB::Raw('*, SUM(a.balance) AS total_balance'))
->join('account_types AS ct', 'ct.parent_id', '=', 'at.id')
->join('accounts AS a', 'a.account_type_id', '=', 'ct.id')
->where('at.parent_id', 0)
->where('a.user_id', $user)
->groupBy('ct.id')
->get();

Laravel 5: LengthAwarePaginator returned JSON not array

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!

Resources