Laravel 强制转换设置日期格式不起作用

Art*_*hur 5 laravel

面临这样的问题。有一个预订模式。Booking 具有字段 time_from 和 time_to。当我致电某种预订时,格式会有所不同。尝试使用 $casts = ['time_from' => 'datetime:mdY']; 不工作!可能是什么问题呢???

模型

class Booking extends Model
{
    use HasFactory;
    protected $casts = [
        'time_from' => 'datetime:m-d-Y',
        'time_to' =>  'datetime:m-d-Y'
    ];
    protected $dateFormat = 'm-d-y';
    protected $fillable = [
        'room_id',
        'time_from',
        'time_to',
        'first_name',
        'last_name',
        'phone',
        'email',
        'special_requirements',
        'when_wait_you',
    ];

    public function room(){
        return $this->belongsTo(Room::class);
    }
}
Run Code Online (Sandbox Code Playgroud)

移民

    public function up()
    {
        Schema::create('bookings', function (Blueprint $table) {
            $table->id();
            $table->bigInteger('room_id');
            $table->dateTime('time_from');
            $table->dateTime('time_to');
            $table->string('first_name');
            $table->string('last_name');
            $table->string('phone');
            $table->string('email');
            $table->text('special_requirements')->nullable();
            $table->string('when_wait_you')->nullable();
            $table->timestamps();
        });
    }
Run Code Online (Sandbox Code Playgroud)

结果

在此输入图像描述

IGP*_*IGP 6

当您将模型转换为数组或 json 格式时,转换就完成了。

class Booking extends Model
{
    use HasFactory;
    protected $casts = [
        'time_from' => 'datetime:m-d-Y',
    ];
}
Run Code Online (Sandbox Code Playgroud)
App\Models\Booking::first()->time_from

=> Illuminate\Support\Carbon { ... }
Run Code Online (Sandbox Code Playgroud)
App\Models\Booking::first()->toArray()['time_from'] 

=> '01-02-2021'
Run Code Online (Sandbox Code Playgroud)
App\Models\Booking::first()->toJson()

=> "{... "time_from":"01-02-2021", ....}"
Run Code Online (Sandbox Code Playgroud)