Accessors in Laravel provide a convenient way to retrieve specific fields or attributes from JSON data. In this article, we will explore how to create an accessor for JSON fields in the context of a Student model.
Let’s assume we have a Student model that represents student information, including their courses and grades. Both information is included in meta
JSON field.
We want to create an accessor to retrieve the courses a student is enrolled in. Here’s how you can achieve this:
use Illuminate\Database\Eloquent\Model; class Student extends Model { protected $appends = ['courses']; public function getCoursesAttribute() { return array_get($this->meta, 'courses', []); } }
In the code snippet above, we define the getCoursesAttribute()
method within the Student model. This method retrieves the value of the “courses” field from the $this->attributes
array, which contains all the model’s attributes. If the “courses” field does not exist, an empty array will be returned as the default value.
After defining the accessor, we include the “courses” attribute in the $appends
array. This ensures that the “courses” attribute will be added as a column during JSON and array serialization.
Now, when you retrieve a student instance, the “courses” attribute will be available as if it were a property of the Student model. For example:
Full code of the Student model:
use Illuminate\Database\Eloquent\Model; class Student extends Model { protected $table = 'students'; // The attributes that are mass assignable protected $fillable = [ 'name', 'meta' ]; protected $casts = [ 'meta' => 'array', ]; /** * The accessors to append to the model's array form. * * @var array */ protected $appends = ['courses', 'grades']; /** * Accessor for retrieving the courses attribute. * * @return array */ public function getCoursesAttribute() { return array_get($this->meta, 'courses', []); } public function getGradesAttribute() { return array_get($this->meta, 'grades', []); } }
By using accessors, you can easily retrieve and manipulate JSON data within your Student model. This approach can be extended to other attributes and models in your Laravel application, providing a flexible way to work with JSON fields.