问题
My DB records are this.
tests table
id date
1 2016-07-01
2 2016-07-31
3 2016-08-01
4 2016-08-15
5 2016-08-31
6 2016-09-01
I wanna choose record by month. Now my code is this.
Controller
$months = \App\Test::where('date', '<=', 'now()')
->orderBy('date', 'desc')
->pluck('date', 'date');
View
{{ Form::select('month', $months, old('month'), ['id' => 'month']) }}
( that generate this. )
<select id="month" name="month">
<option value="2016-07-01">2016-07-01</option>
<option value="2016-07-31">2016-07-31</option>
<option value="2016-08-01">2016-08-01</option>
<option value="2016-08-15">2016-08-15</option>
</select>
But I wanna this.
$months = \App\Test::where('date', '<=', 'now()')
->orderBy('date', 'desc')
// ->format('m').
->pluck('date', 'date');
{{ Form::select('month', $months, old('month'), ['id' => 'month']) }}
( I wanna generate this )
<select id="month" name="month">
<option value="7">7</option>
<option value="8">8</option>
</select>
I wanna use format with pluck but cant do this sadly Any solves?
回答1:
You can do that, through three ways. All of those solutions depend on the fact that the date attribute is not a Carbon instance, which is your case.
- An accessor for the date attribute to return the format your wish:
In your Test Model
Test.php
public function getDateAttribute($value)
{
return Carbon::createFromFormat('Y-m-d H', $value)->format('m');
}
However this will affect the code everywhere.
- The second way, is to create custom attribute.
public function getFormattedDateAttribute()
{
return Carbon::createFromFormat('Y-m-d H', $this->date)->format('m');
}
- The third way is to edit the collection itself.
$months = \App\Test::where('date', '<=', 'now()')
->orderBy('date', 'desc')
->pluck('date');
$months->each(function($month){
return Carbon::createFromFormat('Y-m-d H', $month)->format('m');
});
回答2:
$months = \App\Test::select(DB::raw('to_char(date, \'MM\')'))
->where('date', '<=', 'now()')
->orderBy('date', 'desc')
->pluck('date', 'date');
This will yield you a list of months.
More info
回答3:
Thanks Everyone, I had given up to pickup month from DB yesterday, But Today!! I got TRUE Answer with this code XD. NOTE, This code will work Postgresql only, And where ... now() is too. this is postgres code. Mysql or sqlite have to change DB raw and where code ya.
$months = \App\Test::select(\DB::raw('DATE_PART(\'MONTH\', date) AS MONTH'))
->where('date', '<=', 'now()')
->orderBy('date', 'desc')
->pluck('month', 'month');
来源:https://stackoverflow.com/questions/39095477/can-i-get-custom-date-format-for-plucklists-on-laravel5