In my controller after I create a new Post I return the new post in a post variable. For some reason I don't get the properties with default values back. I noticed that if I set the value to something in controller it does indeed return the properties in the payload.
public function create(Request $request)
{
$validatedData = $request->validate(PostValidator::$create);
$post = new Post();
$post->postcategory_id = $request->input('postcategoryid');
$post->user_id = $request->input('authorid');
$post->thumbnail = $this->uploadFile($request, 'thumbnail', config('app.defaultImage'));
$post->video = $request->input('video');
$post->slug = $this->slugify($request->input('title'));
$post->url = '/publicaciones/'.$this->slugify($request->input('title'));
$post->title = $request->input('title');
$post->body = $request->input('body');
$post->isVisible = false; //IF I DO THIS isVisible is returned in $post variable
$post->save();
$post->load(['postcategory','author']);
return response()->json([
'post' => $post,
]);
}
you can say laravel works like that. default values defined in the database layer is absent in a newly created object. however you can use refresh to refresh the object before returning. and it will have the missing values then.
$post = new Post();
$post->attribute = $request->attribute;
$post->save();
$post = $post->refresh();
return $post;
or you can set default values in the model layer
protected $attributes = [
'isVisible' => false
];
and you will have the default values when returning a newly created object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With