Yigitcanakkaya Diyelim ki bir tur için 3 tane tarih belirlenmiş olsun:
+------------+------------+
| starts_at | ends_at |
+------------+------------+
| 2020-04-10 | 2020-04-15 |
| 2020-04-11 | 2020-04-18 |
| 2020-05-15 | 2020-05-20 |
+------------+------------+
$startsAt = Carbon::parse('2020-03-10');
$endsAt = Carbon::parse('2020-03-15')
// İki tarih arasındaki günleri şu şekilde dizi olarak alabilirsiniz:
// Daha sonra ihtiyacınız olursa foreach ile tek tek hepsine ulaşırsınız:
$period = CarbonPeriod::create($startsAt->toDateString(), $endsAt->toDateString());
// Burada her bir $date Carbon objesi olmuş oluyor
foreach($period as $date) {
// $date->toDateString(); ...
}
// İki tarih arasındaki gün ve gece sayısını şu şekilde bulabilirsiniz:
$daysCount = $startsAt->diffInDays($endsAt);
$nightsCount = $daysCount - 1;
// Diyelim ki turları Tour modeli temsil etsin, bu üstteki tarihleri de TourDate modeli
// Tour::tourDates() → HasMany TourDate şeklinde de ilişkimiz kurulu olsun
// TourDate modeline de selectbox için bir tane accessor tanımlayalım:
// {tarih} / {x} Gece {y} Gün şeklinde bir yazı verecek, gruppaldaki gibi
public function getOptionLabelAttribute()
{
$date = $this->starts_at->format('d F Y');
$daysCount = $this->starts_at->diffInDays($this->ends_at);
$nightsCount = $daysCount - 1;
return sprintf("%s / %d Gece %d Gün", $date, $nightsCount, $daysCount);
}
// Turun seçilebilir tarihlerini almak için:
$tour = Tour::find(1);
$dates = $tour->tourDates()
->whereDate('starts_at', '>=',now()->toDateString())
->get()
// Burada sonuçları aya göre gruplayacağım böylece gruppal sitesindeki gibi
// selectbox içerisinde aylara göre tarihleri bölebileceğim:
->groupBy(function ($date) {
return Carbon::parse($date->starts_at)->format('Y-m-01');
});
// Bu üstteki bana şöyle bir çıktı verecek:
/*
{
"2020-04-01":[
{
"id":1,
"tour_id":1,
"starts_at":"2020-04-10 00:00:00",
"ends_at":"2020-04-15 00:00:00"
},
{
"id":2,
"tour_id":1,
"starts_at":"2020-04-11 00:00:00",
"ends_at":"2020-04-18 00:00:00"
}
],
"2020-05-01":[
{
"id":3,
"tour_id":1,
"starts_at":"2020-05-15 00:00:00",
"ends_at":"2020-05-20 00:00:00"
}
]
}
*/
Şimdi artık bundan bir select oluşturabilirim:
<select>
@foreach($dates as $date => $tourDates)
<optgroup label="{{ \Carbon\Carbon::parse($date)->format('F') }}">
@foreach($tourDates as $tourDate)
<option value="{{ $tourDate->id }}">{{ $tourDate->option_label }}</option>
@endforeach
</optgroup>
@endforeach
</select>
Sonuç:
Ben vanilla yazdım, mantığı anlamanız için