Support the ongoing development of Laravel.io →
Database Eloquent
Last updated 6 months ago.
0

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)

Last updated 6 months ago.
0

Ok a few thoughts that will hopefully help!

  1. PostController->index() uses $post->toArray, should this not be $this->post->toArray() ?
  2. Is post a proper instance of the Post entity?
  3. Try changing your post entity to:
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!

Last updated 6 months ago.
0

@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)

Last updated 6 months ago.
0

@XoneFobic, learn something new everyday! Wasn't sure about that but thought might aswell keep it in. Cheers!

Last updated 6 months ago.
0

@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. :)

Last updated 6 months ago.
0

Sign in to participate in this thread!

LaraJobs

Your banner here too?

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

The Laravel portal for problem solving, knowledge sharing and community building.

© 2022 Laravel.io - All rights reserved.