should a laravel attribute type be cast in its schema?

By default, attributes will be casted to the type of column defined in the table. So, if your column is an integer, then it will be casted as int.

But, what happens if you want to modify this behavior for specific fields? That’s when attribute casting enters the scene.

For example, imagine we have in a table called projects a column named config of type json in which we can store additional configuration elements for each project.

In my case, it’d be useful to be able to handle this data as an array. So, instead of receiving a string or object, we can just deal with a simple array. To do this, we just:

class Project extends Model
{
    // ...

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

    // ...
}

This way, whenever we use Eloquent to fetch projects from the database, each record will have that property as an array. And also, it will be converted back to json when trying to store/update records.

Related to the case you specified (saving element as a string but then retrieve it as an integer) is totally possible of course. You’ll need to set both the accessor and the mutator for that field. For an attribute named number:

/**
 * This will be called when fetching the element.
 */
public function getNumberAttribute($value)
{
    return (int)$value;
}

/**
 * This will be called when storing/updating the element.
 */
public function setFirstNameAttribute($value)
{
    $this->attributes['number'] = (string)$value;
}

Now, a reason to ever need to make this? Well, you could be dealing with a database not properly well designed, or with a production database that is being used by multiple systems and changes in the db are hard to accomplish. In those cases you could make use of this kind of value manipulation to work as you want in your app.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top