I am trying to get unique values in a drop down list. Code for drop down is:
@foreach($admin_bills as $admin_bill)
<?php $month = date('M, Y', strtotime($admin_bill->created_at)); ?>
<option value="{{ $admin_bill->id }}">{{ $month }}</option>
@endforeach
This gives me all the values based on created_at
. For example, if there are multiple entries on same month, it gives me results like
Aug, 2017
Aug, 2017
Aug, 2017
Sep, 2017
Sep, 2017
But if there are multiple entries on same month, I want them to show once in the drop down. So the result will be like:
Aug, 2017
Sep, 2017
I cannot simply use function like array_unique()
here and the $admin_bill->id
should get the first id of unique $month
. How can I do that? Please help. I am using Laravel 5.4
Thank you.
It is recommended that you solve this in the controller. Not in the view. In the controller you can write something like the following:
$admin_bills->pluck('created_at')->map->format('M, Y')->distinct();
I didn't test this but I think it will get you in the right direction.
I am assuming that the created_at
property is automatically parsed to a carbon object. Because that is the way Laravel normally works.
If you move this logic into the controller, you can do it with a simple loop:
$uniques = [];
foreach ($admin_bills as $bills) {
$month = date('M, Y', strtotime($bills->created_at));
if (!in_array($month, $uniques)) {
$uniques[] = [
'date' => $month,
'id' => $bills->id
];
}
}
// Useage
foreach ($uniques as $v) {
$v['id']
$v['date']
}
Try formatting it in your controller:
$admin_bills_formated = $admin_bills->map(function ($item, $key) {
$item->month = Carbon::parse($item->created_at)->month;
return $item;
});
$admin_bills_grouped = admin_bills_formated->groupBy('month');
Assuming your admin_bills
variable is a collection and created_at
field is a Carbon
instance.
In your controller
$adminBillUniqueMonths = $adminBills->unique(function($bill) {
$bill->created_at->format('Ym');
});
and in your view
@foreach($adminBillUniqueMonths as $bill)
<option value="{{ $bill->id }}">{{ $bill->created_at->format('M, Y') }}</option>
@endforeach