How can I print a Laravel Eloquent Model with null values? I want to get a new Question object to include all the fields, just with null
, but instead, it prints a []
.
var app = new Vue({
el: "#survey-form",
data: function() {
return {
survey: {!! $survey !!}
};
},
methods: {
add: function() {
return this.survey.questions.push({!! new App\Question !!});
}
}
});
Given that App\Question
has id
, survey_id
, and text
fields,
(new App\Question())->toJson()
prints []
.
How Can I make it print {"id": null, "survey_id": null, "text": null}
?
For those wondering, I'm trying to get the structure of a question so that I don't have to worry about changing the structure of the JSON in the template if the model structure changes. I know I could easily hardcode the structure with
return this.survey.questions.push({"id": null, "survey_id": null, "text": null});
but with that, every time a column is added to the questions table, I'll have to remember to change that in the template file too. By relying on {!! new App\Question !!}
, I hoped it would reflect the structure automatically.
The model doesn't know about the columns until it queries the database and gets the returned attributes from the query. That is why your new instance doesn't have any attributes.
You will need to fill in the attributes manually, but you can use Laravel to get the column names.
Your code will look something like:
$question = new \App\Question();
// get the columns from the questions table
$fields = \Schema::getColumnListing($question->getTable());
// create an array where the keys are the field names and the values are null
$nullFields = array_fill_keys($fields, null);
// force fill the model instance with the null fields
$question->forceFill($nullFields);
// get your json
$json = $question->toJson();
To combine that all into one line:
(new \App\Question())->forceFill(array_fill_keys(\Schema::getColumnListing((new \App\Question())->getTable()), null))->toJson();
And, if you don't like that second "new" instance, you can use the tap
helper (assuming you're on >=5.3):
tap(new \App\Question(), function ($question) { $question->forceFill(array_fill_keys(Schema::getColumnListing($question->getTable()), null)); })->toJson()