Date Mutators
By default, Eloquent will convert the created_at
and updated_at
columns to instances of Carbon, which extends the PHP DateTime
class and provides an assortment of helpful methods. You may add additional date attributes by setting the $dates
property of your model:
Open User.php model file and implement code as below
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
/**
* The attributes that should be mutated to dates.
*
* @var array
*/
protected $dates = [
'seen_at',
];
}
You may disable the default created_at
and updated_at
timestamps by setting the public $timestamps
property of your model to false
.
When a column is considered a date, you may set its value to a UNIX timestamp, date string (Y-m-d
), date-time string, or a DateTime
/ Carbon
instance. The date's value will be correctly converted and stored in your database:
So, for example
Create Route in Web.php file as below
Route::get('/datemutator ', 'demoController@datemutator')->name('datemutator');
Create demoController and implement code to date mutators
php artisan make:controller demoController -mcr
Open demoController.php in app\Http\Controller folder and implement code as below
public function datemutator()
{
$user = User::find(1);
$user->deleted_at = now();
$user->save();
}
As noted above, when retrieving attributes that are listed in your $dates
property, they will automatically be cast to Carbon instances, allowing you to use any of Carbon's methods on your attributes:
public function datemutator()
{
$user = User::find(1);
return $user->deleted_at->getTimestamp();
}
Date Formats
By default, timestamps are formatted as 'Y-m-d H:i:s'
. If you need to customize the timestamp format, set the $dateFormat
property on your model. This property determines how date attributes are stored in the database:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class demo extends Model
{
/**
* The storage format of the model's date columns.
*
* @var string
*/
protected $dateFormat = 'U';
}