What Is The Use Of Date Mutators In Laravel With Example

admin_img Posted By Bajarangi soft , Posted On 10-09-2020

Mutator allow you to format Eloquent attribute values when you retrieve or set them on model instances. For example, you may want to use the Laravel encrypter to encrypt a value while it is stored in the database, and then automatically decrypt the attribute when you access it on an Eloquent model. In addition to custom accessors, Eloquent can also automatically cast date fields to Carbon instances or even cast text fields to JSON.

What Is The Use Of Date Mutators In Laravel With Example

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

 

Related Post