How to add custom cast type in Laravel?

What is casting in Laravel?

With casting we can transform Eloquent attribute values when retrieving or set them on model instances.

Casting does not require to define any additional methods on model.

The $casts property is an array. The key of the array is the name of the attribute being cast and the value of the array is the type casting the column to.

Supported cast types

The supported cast types are: array, AsStringable::class, boolean, collection, date, datetime, immutable_date, immutable_datetime, decimal:, double, encrypted, encrypted:array, encrypted:collection, encrypted:object, float, integer, object, real, string, timestamp.

We will get details about casting in https://laravel.com/docs/10.x/eloquent-mutators

Now we will create a custom cast type out of the supported cast types mentioned above.

Create custom cast type

We will create JSON custom cast type. With this when the value is added it will be JSON encoded and when fetched the value will be JSON decoded.

To accomplish this we will follow below mentioned steps.

Steps to create JSON custom cast type

Step 1: Creating Casts directory with in app and create Json.php file in it.
Step 2: Creating a custom json cast class in app/Casts/Json.php.
<?php
namespace App\Casts; 
use Illuminate\Contracts\Database\Eloquent\CastsAttributes; 
class Json implements CastsAttributes { 
 public function get($model, $key, $value, $attributes) { 
 return json_decode($value, true); 
 } 
 public function set($model, $key, $value, $attributes) { 
 return json_encode($value); 
 } 
}
Step 3: Attaching App\Casts\Json class to user model.
<?php
namespace App\Models;
use App\Casts\Json; 
...
class User extends Authenticatable
{
...
protected $casts = [ 
			'options' => Json::class, 
		   ];
...
}
Step 4: Now Setting and fetching using JSON custom casting in controller.
<?php
namespace App\Http\Controllers;
use App\Models\User;
class UserController extends Controller
{
public function index(){
$user = User::find(1); 
$user->options = ['key'=>'value']; 
$user->save(); 
$options = $user->options; 
var_dump($options); 
// array(1) { ["key"]=> string(5) "value" }
}
}

Here we see if we dump we get JSON decoded value.

Note: option column is required in user table in database.