Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to eager load only 1 result from many to many relationship Laravel

How can I eager load only one from many to many relationship?

I have two models Application & Applicant

Models\Application.php

public function applicants() {
    return $this->belongsToMany(Applicant::class);
}

public function oneApplicant() {
    return $this->applicants()->first();
}

I'm wanted to paginate on the applications and want to load only one applicant (if they have.)

return Application::stage( $stages )
->stagenot($stageNot)
->refered( $refered, $term )
->with(['oneApplicant'])
->orderBy('created_at','desc')->paginate( $count );

But it isn't working. Getting the first result like this return $this->applicants()->first() will produce an error Call to undefined method Illuminate\Database\Query\Builder::with()

If I also put a limit instead of first return $this->applicants()->limit(1) it will only show one applicant to the last collection.

I also tried to modify the query directly on eager loading call to get the first row

return Application::with(['applicants',  => function( $query ) {
        $q->first();
    }])->orderBy('created_at','desc')->paginate( $count );

But the result is the same as adding a limit(1) on directly on the relation, it will only add one applicant to the last item from collection and the other item have empty array value

Can anybody help :)

Thanks

like image 430
SymmetricsWeb Avatar asked Oct 26 '25 23:10

SymmetricsWeb


1 Answers

I realized its too complex to achieve it myself and ended up using the eloquent-eager-limit package from staudenmeir (big thanks to him, save me hours of work :) )

here's my model

class Application extends BaseModel {
    use \Staudenmeir\EloquentEagerLimit\HasEagerLimit;

    public function applicants() {
        return $this->belongsToMany(Applicant::class);
    }

    public function oneApplicant() {
        return $this->applicants()->limit(1);
    }
}

Then I was able to use it on my controller

return Application::stage( $stages )
    ->stagenot($stageNot)
    ->refered( $refered, $term )
    ->with([
        'oneApplicant',
        'oneApplicant.onePhone:model_id,number',
        'oneApplicant.oneAddress:model_id,state'
    ])->orderBy('created_at','desc')->paginate( $count );

like image 173
SymmetricsWeb Avatar answered Oct 29 '25 23:10

SymmetricsWeb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!