Search an array nested in a laravel collection - php

I have a api call that returns a set of data something like this:
{
"id": 97423,
"visitor_id": 231505,
"domain_sessionidx": 1,
"session_start": "2017-06-01 04:40:07",
"session_end": "2017-06-01 05:22:45",
"session_length": 2558,
"count_pages": 11,
"count_pings": 7,
"created_at": null,
"updated_at": "2017-06-12 18:59:51",
"pages": [
1829,
1811,
1829,
1501,
1829,
1889,
1762,
1686,
1825,
1825,
1825
] },....
I have put this into a variable and made a collection out of it:
$new_var = collect($result);
I am having a problem because I would like to access only the records in the data where pages contains the id 1762. I have been trying with:
$new_var->whereIn('pages',[1762])->pluck('pages')
but I am always getting an empty result. Any help is greatly appreciated.

I feel like you need to filter your $new_var collection and return true if it's pages attribute contains the page you are looking for. For example:
$page = 1762;
$inPages = $new_var->filter(function($collection) use($page){
return in_array($page, $collection->pages);
});
$inPages should now be a subset of $new_var with entries that contain 1762 in their pages array, otherwise it will be an empty Collection. Check here for more information: https://laravel.com/docs/5.4/collections

Related

Get whole object data instead id in Laravel

I have an object with this structure, that I need to get name of source_id in my blade file,
When I try to access that by the way
$data['source_id']['name']
$data->source_id->name
$data->{'source_id'}->{'name'}
I got this error
Trying to get property 'name' of non-object
I just try this $data->source_id, but it return its ID, instead the object,
any suggestion?
{
"id": 4,
"type": "s1",
"source_id": {
"id": 1,
"code": "۱",
"name": "تیل پطرول",
"manager": "نجیب",
"phone": "۰۷۷۲۴۳۴۳۲۱",
"address": "دهمزنگ",
"capacity": "0.00",
"oum_id": 1,
"created_at": "2021-03-02T15:55:20.000000Z",
"updated_at": "2021-03-02T15:55:20.000000Z"
},
"source_type": "STRG",
}
Here is the function to get data
public function loadSale($id){
$base = Sale::findOrFail($id);
if ($base->type == "s1") {
$sale = Sale::with(['saleS1.project.pro_data', 'source_id'])->where('id', $id)->first();
$sale['sales'] = $sale->saleS1;
}
return $sale
}
I could understand your problem. But it is an object not an array. You have to use a loop to access the object. Create a for loop and and inside which you can access the particular field of the object. Hope this helpful
As #MAY mentioned in the comment
I guess the name of your relation and foreign key field is same, that's why you get id when you do this $data->source_id
So I modify the relation and define the source, now I can't access the data simply as before $data->source->name

Laravel - Eloquent to Json, and then sortBy on json object not working

I have this json value that I want to be sorty but for some reason it's not working.
[
{
"id": 15028,
"order_id": 342,
"user_id": 3,
"status": "1",
"priority": "1",
"donedate": null,
"user": {
"id": 3,
"name": "Max"
}
},
{
"id": 15030,
"order_id": 341,
"user_id": 4,
"status": "2",
"priority": "1",
"donedate": null,
"user": {
"id": 4,
"name": "Jon"
}
}
]
This jSon structure is the result of Laravel eloquent object conversion using $object->toJson();
Now I keep this output in my Redis cache. What I want is to when the status and or priority of any order gets changed then I want to sort this jSon and store it back in Redis.
$order_list = collect($json_decoded_with_updated_values);
$order_list = $order_list->sortBy('status')->sortBy('priority');
Redis::set(\GuzzleHttp\json_encode($stich_list_in_collection));
Redis::set("orders_list", $orders_list, 302400);
However, I don't get a sort list. What I want to achieve is that, just like I would run two to three orderBy on an eloquent model like orderBy('status')->orderBy('priority')->get() .. I want to run the same two sortings on this json list.
Thanks in advance.
I figured it out. Actually we don't need to have a call-back as suggested by #brokedid. We can do it like following.
$order_list->sortBy('status')->sortBy('priority')->values()->all();
So I was missing the "->values()->all()" part. I hope if any one runs into the same problem in future, they can get a hint from this.
If you want to sort by multiple Fields, then you could try to sort with a callback-method:
$orderedList = $unorderedList->sortBy(function($item) {
return $item->priority.'-'.$item->status;
});
I wonder what's the result when you choose a different sort direction.
$order_list = $order_list->sortByDesc('status');

Laravel is returning objects with key:value instead of array of objects

I am trying to return Json response as an array of objects. But instead I got response as object of objects. I have condition_question table where I save question_id and condition_id. I want to retrieve all questions which contains particular condition id. And sort them by answers_number. I am new to Laravel, here is my code:
$conditionsIdArray = array($chosenConditionsIds);
$results = Question::whereIn('question_id', function ($query) use ($conditionsIdArray) {
$query->select('question_id')
->from('condition_question')
->whereIn('condition_id', $conditionsIdArray);
})->get()->sortByDesc('answers_number')->take(5);
return response()->json([
'questions' => $results
], 200);
I get response:
{
"questions": {
"0": {
"question_id": 842,
"question_title": "Qui tempora...",
"question_body": "Repellendus non sint...",
"image": "https://lorempixel.com/640/480/?18901",
"question_view_count": 17,
"votes_number": 9,
"answers_number": 9,
"id_user": 9930,
"created_at": "2019-09-07 09:59:05",
"updated_at": "2019-09-08 18:23:41"
},
"28": {
"question_id": 20346,
"question_title": "Quaerat facere...",
"question_body": "Repudiandae culpa ...",
"image": "https://lorempixel.com/640/480/?91963",
"question_view_count": 2,
"votes_number": 2,
"answers_number": 9,
"id_user": 3546,
"created_at": "2019-09-07 10:07:38",
"updated_at": "2019-09-07 10:07:38"
},etc
}
As you can see, I get object with object. I do not want key/value, just simple array of objects type Question.
I am struggling two days now, have tried some different stuff like toArray() but do not know how to solve it. Any help would be most welcome.
If you change the keys in an indexed array, it will believe it has an associate array, due to sorting the index is off. On the Laravel collection there is a values() method, which you can call there that reindex the collection.
return response()->json([
'questions' => $results->values()
], 200);

Get attribute from laravel's "with" closure

I have something like that:
$order = Order::with('user')->where('id', $id)->first();
It returns:
{
"id": 1,
"price": null,
"user": {
"id": 1,
"name": "jon"
}
}
Now inside my laravel code I want to get id of user. How is that possible?
because $order->user returns just null
Since above value returned by Order::with('user')->where('id', $id)->first(); is a collection so try chaining the result with pluck like below
Order::with('user')->where('id', $id)->first()->pluck(user.id);
Let me know if this works for you as I could not replicate it on my machine.

How to save data through objects which are in array in Laravel

I m newbee in laravel. I am sending such type of response through Postman. and in Laravel controller I m getting this response in $request.
[{
"id": 40,
"cname": "Ramesh",
"constraint_value": "",
"r_id": "6",
"rtype_id": null,
"deleted_at": null,
"created_at": null,
"updated_at": null,
"input": "111",
"input2": "111"
}, {
"id": 45,
"cname": "Suresh",
"constraint_value": "",
"r_id": "6",
"rtype_id": null,
"deleted_at": null,
"created_at": null,
"updated_at": null,
"input": "222",
"input2": "222"
}, {
"id": 49,
"cname": "Raj",
"constraint_value": "",
"r_id": "6",
"rtype_id": null,
"deleted_at": null,
"created_at": null,
"updated_at": null,
"input": "333",
"input2": "333"
}]
I am facing difficulty in
How to count the total no of objects in array which I am receiving in $request. I had used count($request) or sizeOf($request) but its returning only 1 although there are 3 arrays. Help me in this.
How to save the data in database through such arrays.I want to save the values of input and input2.
Probably late, but may help someone in the future. First of all. You need to iterate over the array of objects like so
foreach($request->all() as $key => $value){
$model = new Model();
$model->attribute1 = $value['attribute1'];
$model->attribute2 = $value['attribute1'];
$model->attributeN = $value['attributeN']; // where N is infinite # of attr
$model->save();
}
So what is happening is that each time the loop iterates, it create a new object of your Model type inside the loop and assigns the objects attributes from the array key values and persists in DB and repeats until all the objects in the array are finished. The
$model = new Model();
is necessary so that each time loop iterates It creates a new object and persists. The loop may save only one object if u do not create it each time the N iteration occurs. This may happen if u are creating the model object in the constructor where it is instantiated once when the constructor is run.
Hope this helps.
Try to convert it to an array:
$data = json_decode($request, true);
$count = count($data); // Count number of elements.
Model::insert($data); // Insert all elements into DB.
Don't forget to validate any input first and add all fields except timestamps to a $fillable array.
You can try this..
$data = [{},{}]; // your response
$count = 0;
foreach($data as $obj)
{
Model::create($obj); //save the model
$count ++;
}
echo $count // your count
its quit simple
$request ='[ {"id":40,"cname":"Ramesh","constraint_value":"","r_id":"6","rtype_id":null,"deleted_at":null,"created_at":null,"updated_at":null,"input":"111","input2":"111"}, {"id":45,"cname":"Suresh","constraint_value":"","r_id":"6","rtype_id":null,"deleted_at":null,"created_at":null,"updated_at":null,"input":"222","input2":"222"}, {"id":49,"cname":"Raj","constraint_value":"","r_id":"6","rtype_id":null,"deleted_at":null,"created_at":null,"updated_at":null,"input":"333","input2":"333"}]';
$request = (array)json_decode($request, true);
now use them as you usually use .
I got the solution. I was making mistake in sending the data from angularjs.I was directly sending the POST request without creating its object like var data = { 'data':my_request} .That is why request was reeving with instance in laravel. But, as I start sending data by creating its object its working. This was the solution for my first problem. Help me how to store that received data in database.

Categories