usrNotFound
usrNotFound

Reputation: 2800

Laravel Eloquent query 'with'

I have users, images and image_user tables. I am trying to eager load and get all the user with images but limit images to only 4.

Think of it as a gallery. Where user can have one or many images

User Model

public function images()
{

   return $this->belongsToMany(Images::class);
}

This is my query so far.

User::with(['images' => function ($query) {
   $query->limit(4);
  }
])->get();

This query returns user but with empty relationship (images)

Any help would be appreciated.

Cheers

Upvotes: 3

Views: 344

Answers (3)

Phoenix1331
Phoenix1331

Reputation: 71

$user = User::with('images')->limit(5)->get();

Are you aware of php artisan tinker? You can output data via your command line.

Try it with..

App\User::with('images')->limit(5)->get();

..and you'll see 5 users with images, providing your relationships are set up right.

Edited

Sorry, I didn't read your question right.

To limit the images returned for each user you could create a new method on your user model like so.

    public function imageslimit(){

       return $this->belongsToMany(Images::class)->limit(5);

    }

Pass all users to your view from your controller.

$users = User::all();

Then call when looping through all users in your view, just do.

@foreach($user->imageslimit as $image)

   $image->name; 

@endforeach

I tested this and it works fine for me.

Upvotes: 1

Sanzeeb Aryal
Sanzeeb Aryal

Reputation: 3266

Use take() to take only 5 of the images.

$users=User::with('images')->get();
foreach($users as $user)
{
   echo $user->name;
   foreach($user->images->take(5) as $image)
   {
      echo $image;
   }
}

Upvotes: 0

Joseph Silber
Joseph Silber

Reputation: 219910

There's no easy built-in way to do this.

Check out Jarek Tkaczyk's excelent post on this subject:

How to get N related models per parent.

Upvotes: 1

Related Questions