Skip to content

Relationship eloquent in laravel?

In user:

public function posts()
    return $this->hasMany(Post::class);

In post:

public function users()
    return $this->belongsTo(Users::class);

I handle in controller:

$user = Users::find('1')->posts;

Then I get an array and the result returned is exactly what I need.

But when I query this way because I need to get a lot of data, the result is an empty array. What did I do wrong?

In UserController.php:

$listUser = Users::with('posts')
    ->select('name', 'title')
    ->where('type', 1)
    ->get(); // It returns posts as an empty array

Please give me any comments.



You have to select foreign key in posts:

$listUser = Users::select(['id', 'name'])
    ->with(['posts' => function($query) {
    ->where('type', 1)


$result = User::select(['id', 'name'])
    ->with(['posts:user_id, title'])
User contributions licensed under: CC BY-SA
1 People found this is helpful