What Is Date Casting In Laravel Framework With Example

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

In Laravel Attribute casting means, changing the value of an attribute to a particular data type like boolean, integer, strings or array. To cast an attribute value of a Laravel Eloquent model, all you have to do is add them to the $casts property of the model class with their desired type.so today we are going to discuss how to use Attribute casting in laravel

What Is Date Casting In Laravel Framework With Example

Date Casting

When using the date or datetime cast type, you may specify the date's format. This format will be used when the model is serialized to an array or JSON:

So, for example
Open User.php model file and implement code as below

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;


class User extends Authenticatable
{
    
    protected $casts = [
        'created_at' => 'datetime:Y-m-d',//display time and date
         //'created_at' => 'datetime',// we can also give date and time
    ];
}
 


Create Route in Web.php file as below

Route::get('/datecast ', 'demoController@datecast')->name('datecast');
 


Create demoController and implement code to get the name 

php artisan make:controller demoController -mcr


Open demoController.php in app\Http\Controller folder and implement code as below

public function cast()
{
    $user = User::find(1);
    return $user->created_at;
}

above cast function calls from route and display the date and time "2020-09-30T19:15:32.000000Z"

Related Post