1

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();
1
  • In order to get a good answer to your question, please include something you've already tried even if it was completely off. Commented Jul 30, 2019 at 16:17

2 Answers 2

1
$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;
Sign up to request clarification or add additional context in comments.

3 Comments

this is great, but How can I sort the result by distance?
Thank you very much, please help me how to sort by distance and make results in pagination
@AsH i've edited my answer to add a sorting by distance
0

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'];
          });

1 Comment

Argument 1 passed to Illuminate\Support\Collection::map() must be callable, string given, called in

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.