Laravel casts set date format not working

Viewed 2943

faced such a problem. There is a Booking model. Booking has fields time_from and time_to. When I call some kind of Booking want so that the format is different. Tried using $casts = ['time_from' => 'datetime:m-d-Y']; not working! What could be the problem???

Model

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);
    }
}

Migration

    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();
        });
    }

Result

enter image description here

1 Answers

The casting is done when you convert the model to an array or json format.

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

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

=> '01-02-2021'
App\Models\Booking::first()->toJson()

=> "{... "time_from":"01-02-2021", ....}"
Related