First off, I think you need to use $post->toArray()
in you controller.
And the getTagsAttribute might be a bit overkill. I never use it for things like this; think it actually can create a conflict in this case.
I'll edit my mostly used code to suit yours a bit better.
In the Post model
public function tags()
{
return $this->belongsToMany('Tag', 'post_tag', 'post_id', 'tag_id');
}
And in Tag model we turn it around
public function posts()
{
return $this->belongsToMany('Post', 'post_tag', 'tag_id', 'post_id');
}
My suggestion, remove the getTagsAttributes for now and change the controller index to:
public function index() {
$posts = $this->post->with('tags')->get();
return Response::json([
'status' => 'POST_SHOW_SUCCESS',
'posts' => $posts->toArray()
], 200);
}
(Untested)
Ok a few thoughts that will hopefully help!
class Post extends Eloquent {
protected $with = array('tags');
protected $appends = array('tags');
public function getTagsAttribute() {
return $this->tags;
}
public function tags() {
return $this->belongsToMany('Tag');
}
}
Hopefully telling the entity to eager load this relationship will get the data your after!
@cgoosey1, I think (on a working query) if you eagerload something, you don't need to define the same attribute again.
->tags()
calls the Collection and ->tags
will call the data (Correct me if I'm wrong here, but this is how I've seen it work for me)
@XoneFobic, learn something new everyday! Wasn't sure about that but thought might aswell keep it in. Cheers!
@XoneFobic, @cgoosey1: Thank you for your time for giving me ideas on how to solve my problem.
Yes, I should have done this,
$posts = $this->post;
I was recalling my code from my head. Haha.
It appears that eagerloading should do it. Documentation about this feature is lacking though.
Also,
protected $with = array('tags');
I can't find this anywhere before. XD
Would be testing your suggestions later. Great thanks guys. :)
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community