Reputation:
I have session Array of two variables, id and distance, I want to show all stores from DB where ids in session equal to ids in stores also I want to show the distance of every store with store details, please note that Im new to laravel, Thank you
dd(session('storeinfo'));
array:252 [▼
0 => array:2 [▼
"id" => 76
"distance" => "3.23"
]
1 => array:2 [▼
"id" => 77
"distance" => "7.09"
]
Store in DB:
$stores = Storeinfo::all();
Upvotes: 1
Views: 404
Reputation: 17206
$stores = [];
$storeInfos = session('storeinfo');
usort($storeInfos, function($a, $b) {
if (!isset($a['distance'])) {return -1;}
if (!isset($b['distance'])) {return 1;}
if ($a['distance'] == $b['distance']) {
return 0;
}
return ($a['distance'] < $b['distance']) ? -1 : 1;
});
foreach ($storeInfos as $storeInfo) {
$store = Store::find($storeInfo['id']);
if ($store) {
$store->distance = $storeInfo['distance'];
$stores[] = $store;
}
}
return $stores;
Upvotes: 1
Reputation: 4499
You can use whereIn()
function in query builder to filter using arrray of data.
$stores = StoreInfo::whereIn(
'id',
collect(session('storeinfo'))->map->id->toArray()
)
->get()
->map(function($storeDetail) {
//find the matching storeinfo from session.
$storeInfo = collect(session('storeinfo'))
->firstWhere('id', $storeDetail->id);
// set distance
return $storeDetail->distance = $storeInfo['distance'];
});
Upvotes: 0