Skip to main content

Accessor for JSON Fields in Laravel

Leveraging Laravel’s accessors, you can effortlessly retrieve targeted fields or attributes from JSON data, making data retrieval a breeze.

use Illuminate\Database\Eloquent\Model;

class Doctor extends Model
{
    protected $table = 'doctors';

    protected $fillable = [
        'name',
        'extra_info'
    ];

    protected $casts = [
        'extra_info' => 'array',
    ];

    protected $appends = ['specializations'];

    public function getSpecializationsAttribute()
    {
        return array_get($this->extra_info, 'specializations', []);
    }
}
use Illuminate\Database\Eloquent\Model;

class Car extends Model
{
    protected $table = 'cars';

    protected $fillable = [
        'brand',
        'model',
        'specs'
    ];

    protected $casts = [
        'specs' => 'array',
    ];

    protected $appends = ['features'];

    public function getFeaturesAttribute()
    {
        return array_get($this->specs, 'features', []);
    }
}

By continuing to use the site, you agree to the use of cookies.