问题
Currently I have this eloquent select in laravel
$queryBooking = Booking::where('id',$id)->select('starts_at','ends_at')->first();
Now I want to put specific format to starts_at
and ends_at
using this format Y-m-d
Data should be shown somethings like this 2020-05-29
(Y-m-d)
How can I do that using laravel eloquent?
UPDATE
tried the answer of spiny did some modification.
$queryBooking = Booking::where('id',$id)->select('starts_at','ends_at')->first();
$booking = PropertyBooking::where('property_id',$queryBooking->property_id)
->selectRaw(
'DATE_FORMAT(`starts_at`, "%Y-%m-%d") AS `starts_at`, DATE_FORMAT(`ends_at`, "%Y-%m-%d") AS `ends_at`'
)->get();
return view('admin.pages.property_request.edit', compact('property_request','booking'));
in my blade tried to log it using js says like this
回答1:
Just add some properties to your booking. The date attribute converts the column to carbon. The dateFormat attribute is the default format for converting dates to String
example
class Booking extends Model
{
protected $dates = ['starts_at','ends_at'];
protected $dateFormat = 'Y-m-d';
....
}
回答2:
How about this:
->selectRaw(
'DATE_FORMAT(`starts_at`, "%Y-%m-%d") AS `starts_at`, DATE_FORMAT(`ends_at`, "%Y-%m-%d") AS `ends_at`'
)
Also you can use it as a scope:
public function scopeSelectStartEndDates($query) {
return $query->selectRaw(
'DATE_FORMAT(`starts_at`, "%Y-%m-%d") AS `starts_at`, DATE_FORMAT(`ends_at`, "%Y-%m-%d") AS `ends_at`'
);
}
$model = Model::selectStartEndDates()->first();
来源:https://stackoverflow.com/questions/61767273/convert-date-format-to-y-m-d-using-larave-eloquent-raw-select