How to access nested json objects without json_decoding the collection - laravel

I have the following data structure:
[
{
"id": 1,
"customer_id": "11",
"customer_name": "Vic",
"cheque_withdraw": {
"id": 2,
"request_date", "2019-03-30"
}
}
]
I have gotten this data from multiple tables through the following code;
$paginator = Cheque::with(['chequeWithdraw' => function($query){
$query->where('withdraw_status' , 'withdrawn');
}])
->paginate(5);
How do I access the nested json object request_date without having to convert my collection to an associative array? The reason why I do not want to convert the collection to an associative array is because I am having challenges paginating the data that has been json decoded.
I am currently trying to access the request_date in my blade file this way;
#foreach($paginator as $cheque)
{{ $cheque->cheque_withdraw->request_date }}
#endforeach
However, I am getting the following error;
Trying to get property 'request_date' of non-object

Actually you have chequeWithdraw and not cheque_withdraw
#foreach($paginator as $cheque)
{{ $cheque->chequeWithdraw->request_date ?? 'NA'}}
#endforeach
You might be trying to convert laravel collection to json or array. laravel convert camel case to snake case . So you were getting it for json not for laravel template.

Related

append to a field of array with eloquent

I have an application with laravel and mongodb. With elequent iam trying to append a new value to an array stored in a field.
So this is an example of a document. Iam trying to append a new value to the projects field.
{
"_id":{
"$oid":"5f80513714450000a6007c90"
},
"organization_id":"5f80304214450000a6007c81",
"user_id":"5f80513714450000a6007c8f",
"status":true,
"role_id":"5c148783fe412ba8333074ec",
"company_id":"5f80511f14450000a6007c8e",
"updated_at":{
"$date":"2020-11-09T18:42:03.000Z"
},
"created_at":{
"$date":"2020-10-09T12:01:59.000Z"
},
"projects":[
"5fa33513416100008d0070ba",
"5f80429814450000a6007c85",
"5f80436714450000a6007c86"
]
}
in my model i have created this method
public function push_user_projects($data, $where_data) {
return UserAccountsModel::where($where_data)->put($data);
}
The where_data works good. The method finds the correct documents to update.
But what doesent work is the pushing part. The following is what i put into data parameter
$data = array(
'projects' => array(
$projectData["_id"]
)
);
And when i se the result a complete new array has updated the projects field with the new value. But i want to append the value to the existing array. Can someopne help me?
To push another element into your data variable under 'projects'
$data['projects'][] = $projectData["_id"];

Laravel: how to get value from query builder object

I am new in laravel. i have a table but dont have model for this. I am using below to fetch record.
$classes = DB::table('school_classes')->get();
return view('classes', ['allClass' => $classes]);
it returns below:
[{"id":1,"register_school_id":1,"class":"I","section":"A","created_at":"2020-03-19 00:00:00","updated_at":"2020-03-19 00:00:00"},
{"id":2,"register_school_id":1,"class":"I","section":"B","created_at":"2020-03-19 00:00:00","updated_at":"2020-03-19 00:00:00"},
{"id":3,"register_school_id":1,"class":"I","section":"C","created_at":"2020-03-19 00:00:00","updated_at":"2020-03-19 00:00:00"}, {"id":4,"register_school_id":1,"class":"I","section":"D","created_at":"2020-03-19 00:00:00","updated_at":"2020-03-19 00:00:00"},
{"id":5,"register_school_id":1,"class":"I","section":"E","created_at":"2020-03-19 00:00:00","updated_at":"2020-03-19 00:00:00"}]
how I can pick the value separately of each item... i tried foreach but getting error.
plz help. thanks in advance.
The query builder returns a Illuminate\Support\Collection instance. You can access the collection as below:
#foreach($allClass as $class)
{{ $class->id }}
#endforeach
Also check Collections
You want to get data in array format, then you can use "toArray" & also easily access data using foreach loop Laravel function.
$classes = DB::table('school_classes')->get()->toArray();
return view('classes', ['allClass' => $classes]);

How to get random row in object variable in Laravel?

Sorry for my bad english, I want to get a single row in my object. And I want that in random order. Im using array_rand() and it only return errors as stated below:
ErrorException: array_rand() expects parameter 1 to be array, object given in file C:\xampp\htdocs\user\TestProject\app\Http\Controllers\TestController.php on line
Here is my object.
"my_list": [
{
"id": 1,
"name": "My Name Test",
"address": [
{
"id": 1,
"city": "Manila",
"country": "Philippines"
}
]
},
{
"id": 2,
"name": "Your Name Test",
"address": [
{
"id": 2,
"city": "Cebu",
"country": "Philippines",
}
]
}
]
The problem is I want only to get a single row to the my_list which is object and not an array.
Here is my code.
$course = Course::where('id', 1)->with('my_list')->first();
$random_list = array_rand($course->my_list);
return $random_list;
I also try adding number of row in the array_rand like this.
$random_list = array_rand($course->my_list, 1);
But still not working.
What did I missed?
Any Eloquent query returns, by default, a Collection, even for the underlying relationships. Since you are working with one, this should work:
$course->my_list->random();
This will return only one item. If you want more, you could pass an argument to the random() method specifying the count of items you want.
For more information, check the documentation.
This Object is a Laravel collection. Please refer to the collection documentation.
https://laravel.com/docs/5.7/collections#method-random
You can try $course->my_list->random()
If you still wanna do this with your approach, can you try get_object_vars function to cast object into array.
$array = get_object_vars($object);
so that you can use them as an array in array_rand.
You might get an error, hence that it's an multi-dimensional array. Let me know so i may update.
Update for multidimensional:
Please refer to this.
// The second parameter of json_decode forces parsing into an associative array
$array = json_decode(json_encode($object), true);
try this:
$course = Course::where('id', 1)
->with(['my_list' => function($query) {
$query->inRandomOrder();
}])->first();
return $course->my_list;
Try this method:
$course = Course::where('id', 1)
->with(['my_list' => function($query) {
$query->inRandomOrder()->first();
}])->first();
return $course->my_list;
this method is more efficient since you will only get 1 row from my_list not like when you use $course->my_list->random() which retrieves all data and from there select a random row.
$random_list = $course['my_list']->random(number);
ps: number = number of element you want to get ,

How to show json data in laravel

i have json array from return $data->group, here the result:
[{
"id": 2,
"name": "Grup 1",
"created_at": "2016-03-16 02:09:15",
"updated_at": "2016-03-16 02:09:15",
"pivot": {
"cabang_id": 28,
"group_id": 2
}}]
i want to "id" and "name" from this data.
i have tried using $data->group->id and $data->group->name but error Undefined property: Illuminate\Database\Eloquent\Collection::$id
how can i take from $data->group?
If you consider the error:
Undefined property: Illuminate\Database\Eloquent\Collection::$id
Then it shows that you're dealing with a Collection object. You can access a Collection's attribute's using the get('key') method as user Alexy Mezenin mentioned.
So you would do something like this in your case:
$data->group->get('id')
Check the docs/api for further details:
Docs: https://laravel.com/docs/5.2/collections#method-get
Api: https://laravel.com/api/5.2/Illuminate/Database/Eloquent/Collection.html#method_get
Normally you can make use of an Eloquent model's magic methods to access its attributes directly by their key name as you were trying to do in the code sample you gave, i.e. $data->group->id. I believe this isn't working for you because you've already returned the data as json, if you would access the object before returning it as json then you would probably be able to access the attributes using the magic methods.
Try to use ->get('id') on the object with json data. Or $request->input('id') where $request is your Request object.

Getting Records with multiple ids in eloquent

Hello i am posting the id of several items along with their quantities to my server eg.:
[{"id": "1", "quantity": "2"}, {"id": "2", "quantity": "5"}, {"id": "3", "quanity": "10"}]
Now on my server I need to validate each of these ids and get certain values from their respective rows in my database table.
What i simply want to do is this:
foreach ($items as $item)
{
$row = Items::find($item);
$price = $row->price;
}
But here i am wondering if the foreach loop will have a huge impact on speed and performance since the items may be many.
My question is is there a way of doing this in laravel without using a foreach, loop, like a query that can fetch data based on an array of ids.
If you want to take all the price attributes of certain ids you can use query's builder whereIn method to achieve this.whereIn accepts an array of values and returns the rows corresponding to these values.It's also very cost efficient when it comes to performance
I see you are passing a json string, so if you where to use whereIn one solution might be like the following:
Example
//json string
$json = '[{"id": "1", "quantity": "2"}, {"id": "2", "quantity": "5"}, {"id": "3", "quanity": "10"}]';
//convert json to array
$json_toArray = json_decode($json,true);
//get id values from array
//If you are using php 5.5+ this will work, if you are using an older version you can use
//array_map method like this: $array_ids = array_map(function ($array) {return $array['id'];}, $json_toArray);
$array_ids = array_column($json_toArray, 'id');
//Finally execute the query
//Using Eloquent
$result = Items::whereIn('id', $array_ids)->select('price')->get();
//Using the Query Builder
$result = DB::table('items')->whereIn('id',$array_ids)->select('price')->get();

Resources