Auto unserialize column while fetching the model, only if it contains serialized array – Laravel 7/8

Hey buddy, yesterday I tried to auto unserialize a column if it contains the serialized array in Laravel. But the issue was that sometimes it contains plain text not the serialized array.
I was using the laravel eloquent accessor to auto unserialize the column value. Like below
<?php namespace App\Models; use Illuminate\Database\Eloquent\Model; class ExampleMeta extends Model { /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'name', 'meta_key', 'meta_value' ]; public function getMetaValueAttribute($value) { return unserialize($value); } }
But the issue was it started to throw an error when the column contains plain string not the serialized array.
After some research I found the solution as below.
public function getMetaValueAttribute($value) { return @unserialize($value) !== false ? unserialize($value) : $value; }
Now, it will auto unserialize column value only if it contains the serialized array otherwise will return the same value.
If you have any query plz let me know in the comment below.