Sunday, April 16, 2017

Return class variable of a Laravel Model in JSON

I have the following model class

class MyModel extends Model {
    public $some_variable; // I don't want to store this in the database
    protected $fillable = ['column1', 'column2'];

In the controller:

$model = MyModel::find(2);
$model->some_variable = "some value"; // Dynamically calculated each time
return response()->json($model);

The response contains all the columns from MyModel but does not contain $some_variable. Why could this be happening? Are class variables transient by default?



via Gaurav Bhor

Advertisement