omor faruk
omor faruk

Reputation: 81

Laravel eloquent pagination call in relational database

I have an user. User create many ads.I want to see users details with ads where ads shown by paginate. For this, i make two model(User & Ads)

public function user(){

     return $this->hasOne(User::class, 'id', 'user_id');
}

public function ads(){

    return $this->hasMany(Ads::class, 'user_id', 'id');
}

In controller i call like this:

$users = Ads::with(['user'=> function ($q) use ($id){
        $q->where('id',$id);
    }])->paginate(2);

But here user's details are shown when forelse loop are called. But i don't want this. So, How can i get user's details with ads's pagination?

Upvotes: 3

Views: 77

Answers (1)

HerickC
HerickC

Reputation: 344

I think you're overcomplicating. You has two models. In User, you can put this relationship:

public function ads(){
    return $this->hasMany(App\Ad, 'user_id', 'id');
}

In Ads model, you put this relationship:

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

In your controller, you simple call like this:

//If you want a list of User's Ads
$user = User::find(1);
$userAds = $user->ads()->paginate(2); //you paginate because can be many

//If you want the details from a user who made the Ad #1
$ad = Ad::find(1);
$user = $ad->user; //Don't need paginate because is only one.

Upvotes: 1

Related Questions