How to cast time in laravel?

Member

by gilbert , in category: PHP Frameworks , 6 months ago

How to cast time in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by hal.littel , 6 months ago

@gilbert 

In Laravel, you can cast time using the castAsTime method in your model.


Here's how you can cast time in Laravel:

  1. Define the column in your database table that you want to cast as time. For example, if you have a column called start_time in your appointments table that you want to cast as time, you should define it as a time type in your migration file.
  2. In your model file (e.g. Appointment.php), add the following code to cast the start_time column as time:
1
2
3
protected $casts = [
    'start_time' => 'time',
];


Now, whenever you retrieve the start_time column from the appointments table, Laravel will automatically cast it to a time format.