0

I have some Eloquent Model with hidden payload field

In some places I want to include that field to JSON representation. I do it with makeVisible method:

$models->makeVisible('payload');

But I don't think it's good OOP code (SRP, DIP, DRY rules, whatever). I would like to hide it behind some abstraction by having some reusable method, like withPayload(), sitting inside my Model class. Is there any way to achieve this in Laravel? Maybe somehow with Query Scopes and pluck method?

3 Answers 3

2

I think the way you're currently using makeVisible is fine. You won't be gaining anything by hiding ->makeVisible('payload'); behind another method. It would be a non-standard way of doing things and the next developer would have to go and learn and remember what the new method does.

$hidden and makeVisible makes it clear to the next developer that the data is possibly sensitive data and must not be visible to all users. If you think you might make the data visible more often than keeping it hidden, consider to either add the field to the $visible array or remove both the $visible and $hidden arrays (if you're not using it for any other fields), and use the makeHidden method to hide the data when you need to.

0

I suggest you to dive into fractals (spatie/laravel-fractal is a nice wrapper around that) and put there the logic for representing your model as JSON.

There you can define the base structure of your JSON output (i.e the fields that you always have) and use an include wherever you need your specific fields.

0

I think the method you're looking for is :

Model::setVisible('field')

From => this

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.