Hello everyone ,
I have a question about using Scope, Paginate, and HasMany Relationship together...
In a Batch Model
/**
* A Batch has many applicants
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function applicants()
{
return $this->hasMany('App\Applicant');
}
By relationship defined, I can access Applicants in a specific Batch using $batch->applicants,
However, what I have to do if I want Applicants result being searched by scope and paginated as well ?
I did something for pagination but have no idea to apply scope search into this accessor
/**
* accessor
* Return Applicants linked to this Batch
*
* @return int
*/
public function getRecordsAttribute()
{
return $this->applicants()->paginate(12);
}
Applicant Model
/**
* Scope a query to search by keyword
*
* @param $query
* @param $keyword
* @return \Illuminate\Database\Eloquent\Builder
*/
public function scopeSearch($query, $keyword)
{
return $query->where(function($query) use ($keyword) {
$query->where('code', 'LIKE', "%{$keyword}%")
->orWhere('name', 'LIKE', "%{$keyword}%")
->orWhere('foo', 'LIKE', "%{$keyword}%")
->orWhere('bar', 'LIKE', "%{$keyword}%");
});
}
Please advice, thanks a lot
Ps - result will return in JSON and not for blade template,