Another way to do accessors and mutators

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 the value will be stored in the database.

1<?php
2 
3namespace App\Casts;
4 
5use Carbon\Carbon;
6use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
7 
8class TimestampsCast implements CastsAttributes
9{
10 public function get($model, string $key, $value, array $attributes)
11 {
12 return Carbon::parse($value)->diffForHumans();
13 }
14 
15 public function set($model, string $key, $value, array $attributes)
16 {
17 return Carbon::parse($value)->format('Y-m-d h:i:s');
18 }
19}

Then you can implement the cast in the model class.

1<?php
2 
3namespace App\Models;
4 
5use Illuminate\Foundation\Auth\User as Authenticatable;
6use App\Casts\TimestampsCast;
7use Carbon\Carbon;
8 
9 
10class User extends Authenticatable
11{
12 
13 /**
14 * The attributes that should be cast.
15 *
16 * @var array
17 */
18 protected $casts = [
19 'updated_at' => TimestampsCast::class,
20 'created_at' => TimestampsCast::class,
21 ];
22}

Tip given by @AhmedRezk

Like our articles?

Become a Premium Member for $129/year or $29/month
What else you will get:
  • 22 courses (477 lessons, total 38 h 20 min)
  • 2 long-form tutorials (one new every week)
  • access to project repositories
  • access to private Discord