Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search an array nested in a laravel collection

Tags:

php

laravel-5

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.

like image 921
garage days development Avatar asked Jun 27 '17 18:06

garage days development


1 Answers

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

like image 83
Tim Lewis Avatar answered Oct 12 '22 23:10

Tim Lewis