I am trying to define a model mutator
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Custom_fields extends Model
{
protected $table = 'custom_fields';
public function setContentAttribute($value){
return unserialize($value);
}
}
and on test controller, tried
Custom_fields::all()[0]->content;
Unfortunately, it is not working; the value is still not an array (serialize)
I want to access the field content
and unserialize the value of the field so I can get an array automatically on retrieve, but it's not working.
You're trying to "get an array automatically on retrieve" with a method called
setContentAttribute
. You are confusing accessors and mutators. As the method name implies, the mutator is called when you set thecontent
attribute.To create an accessor that is called when you get the
content
attribute:Likely if this data is to be stored in a serialized form you want your mutator to look like this:
But really, you should not be using these serialization functions at all. Laravel can natively convert objects to JSON for storage in a database. Simply define the property in your model's
$casts
property and data will be converted automatically when getting or setting the property.