I want to have unique mounths in SELECT. I find out i have to use GROUP BY. But it doesnt work this way:
@foreach($months as $month)
<option value="{{ $month->id }}">{{ Carbon\Carbon::parse($month
->date)
->format(' F ')
->groupBy('date') }}</option>
@endforeach
How to use groupBy in this way? Because it looks like this right now without GROUP BY:
My Laravel Controller:
public function index()
{
$users = User::all(['name', 'id']);
$months = RouteInfo::all(['date', 'id']);
return view('admin.index', compact('users', $users, 'months', $months));
}
Thank you for your help
You need just filter items before show
@php
$uniqueMonth = [];
foreach($months as $key=>$month){
$month = Carbon\Carbon::parse($month->date);
$uniqueMonth[$month->format('m')] = $month->format(' F ');
}
ksort($uniqueMonth); // sorting months
@endphp
@foreach($uniqueMonth as $key=>$month)
<option value="{{ $key }}">{{ $month }}</option>
@endforeach
You could do something like this, within your controller.
$months = RouteInfo::all(['date', 'id'])->groupBy(function($month) {
return Carbon::parse($month->date)->format('F');
});
Then within your view
@foreach($months as $month)
<option>{{ $month }}</option>
@endforeach
This is untested, please let me know if it works for you or if there are any errors.