Custom Cases instead of 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 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

Like our articles?

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

Recent New Courses