Reputation: 3429
I am trying to learn using AngularJs with Laravel. I have read and watched many tuts but I could not find any for using Laravel relationships. I have belongsTo-many relationships between my Post and Author model.When using blade I can get author names using {{$post->author->name}}
Now I am trying to get for angularjs.
class Post extends Eloquent {
public function author()
{
return $this->belongsTo('Author');
}
}
class Author extends Eloquent {
public function posts()
{
return $this->hasMany('Post');
}
}
class UserController extends BaseController {
public function getIndex(){
$posts = Post::where('id','<','10')->get();
return Response::json($posts);
}
}
With the js files :
// public/js/controllers/mainCtrl.js
angular.module('mainCtrl', [])
.controller('mainController', function($scope, $http, Post) {
$scope.postsData = {};
// loading variable to show the spinning loading icon
$scope.loading = true;
Post.get()
.success(function(data) {
$scope.posts = data;
$scope.loading = false;
});
//dont know how to get author here in foreach method
angular.forEach($scope.posts,function(post)...
});
// public/js/services/commentService.js
angular.module('postService', [])
.factory('Post', function($http) {
return {
// get all the posts
get : function() {
return $http.get('/api/posts/');
}
}
});
<div class="comment" ng-hide="loading" ng-repeat="post in posts">
<h3>Comment #{{ post.id }} </h3> <p>{{post.title}}</p>
{{post.author_id}} / {{post.author.name}}
</div>
I am close to solution but still confused how do I get the author name in Post service. Any helps are appreciated.
Thanks
Upvotes: 3
Views: 1841
Reputation: 3536
In your user controller, eager load the author when retrieving the posts, this will allow it to be accessed in angular via post.author
public function getIndex(){
$posts = Post::with('author')->where('id','<','10')->get();
return Response::json($posts);
}
Upvotes: 2