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!