2

Problem

I have two classes, Users & Posts. A user "hasMany" posts and a post "belongTo" a user. But when I call "User::all()" it doesn't automatically pull the users posts for obvious reasons, because if my user had relations to 100 different tables pulling all users would start to become pretty chunky.

Question

Is there a way to pull all users and all user->posts in one or few lines of code without going through a foreach loop?

I know i can use a mutator but the problem I have is my field is called user_id and i have tested it with this code:

public function getUserIdAttribute($id)
{
    return User::find($id);
}

But it will replace "user_id" field value with a user object, Id rather have it set to its own "temporary user" field within the result. I'm trying to find best practice!

Thank you in advance.

Saurabh Mistry
  • 12,833
  • 5
  • 50
  • 71
Kenziiee Flavius
  • 1,918
  • 4
  • 25
  • 57
  • [The Laravel documentation is very good](https://laravel.com/docs/5.7/eloquent-relationships#eager-loading), you will have a much better feeling for what you can do and how to do it if you have a quick read. – Don't Panic Feb 08 '19 at 12:22

1 Answers1

1

What you're looking for is called Eager Loading

Inside your post model :

class Post extends Model
{

    protected $table='posts';
    public $primaryKey='id';

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

 }

now you want to get post with user use below code :

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

inside your user model :

  class User extends Model
   {

      public function posts(){
        return $this->hasMany('App\Model\Post');
      }

  }

now you want to get a user with all posts :

$user=User::where('id',$id)->first();
$user_posts=$user->posts;
Kenziiee Flavius
  • 1,918
  • 4
  • 25
  • 57
Saurabh Mistry
  • 12,833
  • 5
  • 50
  • 71