sdbruder's avatar

Virtual fields, it is possible?

I have an underlying json field but I want to expose the individual json fields as virtual fields in the model, it is possible ?

I've create getters for my virtual fields, appended them in the $appends and created an ::saving event to try to create the json based on the individual values, but I can't get the values to build it with.

EDIT: If I include my virtual fields in the $fillable array I get the values, but then Eloquent push them to the underlying INSERT, giving me an obvious SQL error, there is no such column.

Any suggestions ?

0 likes
10 replies
SimplyCorey's avatar

What is a virtual field? Is this a field you are creating on the fly using the data saved in the model? If so, why don't you merge this data with array_merge after you gather the data from the model? Am I misunderstanding?

sdbruder's avatar

I've got it, but it is the ugliest hack that I've ever done in Laravel:

It's possible, but you need to purge them from the attributes array in an ::saving event to prevent your virtual fields to be in your INSERT sql.

So the question now is, there is a cleaner way to do it?

sdbruder's avatar

"virtual field" -> a field / attribute that exists in my Model but there is no equivalent column in the underlying table.

In my case, imagine a column MyJsonSackOfValues filled in with '{"attribute1" => "value#1", "attribute2" => "value#1", "attribute3" => "value#1"}'.

I want to access $myModel->attribute1, $myModel->attribute2 and $myModel->attribute3.

martinbean's avatar

@sdbruder Look at the Eloquent section in the Laravel documentation for “appends”. That’s what you’re after, as I guess you’re coming from a CakePHP background.

2 likes
squigg's avatar

Your setters and getters should only really update the attributes field to values as it should be stored in the database.

A cleaner way might be to just store your attributes in a single field as an array (using array_set and array_get in your various getters/setters for deep dot notation), and then cast this to JSON on save/load using standard Laravel array cast on the field.

http://laravel.com/docs/5.1/eloquent-mutators#attribute-casting

sdbruder's avatar

I think (hope, actually!) that what I need will be in Laravel 5.2 with the JSON support that is been planned to support mysql 5.7 and the new json type / features.

Metable is in the right direction, but I've already have a JSON column in my table where resides all the attributes that I want exported in the model (to use form model binding and so on).

"appends" only solves the ->toArray() and JSON exports, not the whole solution that I need.

As I said, I've already solved it in hackish way, I'll revisit it when my TODO list gets shorter.

Thank you all.

Please or to participate in this conversation.