In case you are going to use the same accessors and mutators in many models , You can use custom casts instead.
Just create a class that implements CastsAttributes interface. The class should have two methods, the first is get to specify how models should be retrieved from the database and the second is set to specify how the value will be stored in the database.
namespace App\Casts; use Carbon\Carbon;use Illuminate\Contracts\Database\Eloquent\CastsAttributes; class TimestampsCast implements CastsAttributes{ public function get($model, string $key, $value, array $attributes) { return Carbon::parse($value)->diffForHumans(); } public function set($model, string $key, $value, array $attributes) { return Carbon::parse($value)->format('Y-m-d h:i:s'); }}
Then you can implement the cast in the Model class.
namespace App\Models; use Illuminate\Foundation\Auth\User as Authenticatable;use App\Casts\TimestampsCast;use Carbon\Carbon; class User extends Authenticatable{ /** * The attributes that should be cast. * * @var array */ protected $casts = [ 'updated_at' => TimestampsCast::class, 'created_at' => TimestampsCast::class, ];}
Tip given by @AhmedRezk
Enjoyed This Tip?
Get access to all premium tutorials, video and text courses, and exclusive Laravel resources. Join our community of 10,000+ developers.
Recent Courses
[NEW] Building a Typical Laravel SaaS
8 lessons
1 h 07 min
Laravel Coding with AI Agents: Cursor, Claude Code, Codex
5 lessons
1 h 01 min
How to Build Laravel 12 API From Scratch
28 lessons
1 h 21 min