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"