I want to display data based on ranges within a drop down menu list.I currently have singular values where i would select the value 10 and it would display all values that = 10.
Now i want to have a drop down menu with the options of 5-10, 11-15, 16-20 and i expect it to display all data within those ranges. See code below
Search.php
<select name="distance" id="distance" class="form-control input-lg dynamic" data-dependent="state"> <option value="">Choose an item</option> @foreach($distances as $distance) <option value="{{ $distance }}">{{ $distance }}</option> @endforeach </select>
Search.Controller.php
public function index(Request $request) { $distances = DB::table('posts')->select('distance')->distinct()->get()->pluck('distance'); $postsInRange = $request->has('distance') ? Post::where('distance', $request->distance)->get() : []; return view('Pages.search', [ 'distances' => $distances, 'posts' => $postsInRange ]); } public function store(Request $request) { // This will return all request data to your screen. return $request->all(); return view('Pages.search'); }
How would i manage to display the the data using data ranges instead of singular values.
Advertisement
Answer
You can use collection’s groupBy
function:
$distancesByGroup = DB::table('posts') ->distinct() ->pluck('distance') ->groupBy(function ($item, $key) { return (int) ((int) $item / 5); });
And on your blade:
@foreach($distancesByGroup as $group => $distances) <optgroup label="{{ $group * 5 }} - {{ ($group + 1) * 5 }}"> @foreach($distances as $distance) <option value="{{ $distance }}">{{ $distance }}</option> @endforeach @endforeach
Note: I haven’t tested it but it gives you the idea.