There seems to be a problem with fetching the name attribute along with the title and body attributes. The name appears empty on page refresh but shows up automatically upon submission.
Interestingly, angularjs is unable to retrieve the name successfully.
Please note: This issue is occurring while using laravel.
Here is an example scenario:
Server side implementation:
PostController
public function getPosts() {
$posts = Post::with('user')->get();
$response = new Response(json_encode($posts));
$response->headers->set('Content-Type', 'application/json');
return $response;
}
public function storePost(Request $request) {
$data = request()->validate([
'title' => 'required|max:120',
'body' => 'required|max:1000'
]);
$data['user_id'] = auth()->user()->id;
$data['name'] = auth()->user()->name;
$post = Post::create($data);
$response = new Response(json_encode($data));
$response->headers->set('Content-Type', 'application/json');
return $response;
}
Main.js
$scope.myposts = {};
$scope.addPost = function() {
$http.post('/auth/post', {
title: $scope.post.title,
body: $scope.post.body
}).then(function(data, status, headers, config) {
console.log(data);
$scope.myposts.push(data.data);
});
$scope.post.title = '';
$scope.post.body = '';
};
$scope.deletePost = function(post) {
var index = $scope.myposts.indexOf(post);
if (index != -1) {
$scope.myposts.splice(index, 1);
}
$http.delete('auth/post/' + post.id);
};
$scope.getPosts = function() {
$http.get('/auth/posts').then(function(data) {
$scope.myposts = data.data;
}).then(function(data, status, header, config) {});
};
HTML:
<div id="mypost" class="col-md-8 panel-default" ng-repeat="post in myposts">
<div id="eli-style-heading" class="panel-heading">
<% post.title %>
</div>
<div class="panel-body panel">
<figure>
<p>
<% post.body %>
</p>
by:
<p>
<% post.user.name %>
</p>
</figure>
<span><button ng-click="deletePost(post)">x</button></span>
</div>
</div>
When adding content without refreshing asynchronously,
Upon page refresh,
Above logs may differ based on the post.