qwe001 qwe001 - 3 months ago 18
PHP Question

Can I get custom date format for pluck(lists) on Laravel5?

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?

Answer
$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

Comments