1
votes

I'm building an application that has Angular on the front-end and Laravel on the back. My question is, how do I return/retrieve the user's fullname by using their "author_id" on the posts table against "user_id" on the users table? I have a users table and a posts table looking like this:

users table
user_id | fullname | email | password | active

posts table
post_id | author_id (FK-user_id on users table) | text | timestamps

My User Model looks like this:

public function post()
{
    return $this->hasMany('Post', 'author_id');
}

And my Post Model looks like this:

public function user()
{
    return $this->belongsTo('User', 'author_id');
}

Assuming my routing is correct (it is, I can provide it if need be), my PostController has this method for retrieving Posts:

public function getAllPostsByUserID($user_id)
{
    $posts = Post::where("user_id", "=", $user_id)
                            ->get();

    if($posts) {
        return Response::json($posts);
    } else {
        return Response::json(array('flash'=>'No posts by this user.'),500);
    }
}

Right now, I am retrieving a JSON that has all the user's posts, but because the posts table uses author_id, I can't display the user's name, only his ID. I've seen how this works on Laravel/Blade where you can chain methods and then access the user's fullname because of the Eloquent relationship of hasMany or belongsTo, but I can't seem to figure out how to do this while returning a JSON to the Angular side.

Thanks in advance!

1
actually no difference using blade or angular in logic,did you handle by the way?MstfAsan

1 Answers

0
votes

In order to retrieve all posts of a user, you could do the following:

$user = User::with('post')->whereUserId($user_id)->first();

This will give you the $user object and you will be able to access collection of user's post with

$posts = $user->post;

It's also not neccessary to do:

return Response::json($posts);

When you return a Collection or Eloquent object Laravel will serialize it to JSON automatically. If you switch to the code above to fetch user with their posts, it will be enough to just do:

return $user;

UPDATE:

In order to fetch a collection of posts with related users, you can do:

$posts = Post::with('user')->get();

You'll get a collection of Post objects and each of them will have a user attribute holding the related user.