Skip to content

Instantly share code, notes, and snippets.

@Artistan
Last active May 3, 2024 17:47
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Artistan/fea3e21f149fdf845e530299bcff37d4 to your computer and use it in GitHub Desktop.
Save Artistan/fea3e21f149fdf845e530299bcff37d4 to your computer and use it in GitHub Desktop.
Paginator with relations... load the relations on the model

Scout paginator with relations...

Scout cannot do a standard relation call because it is not using Eloquent behind the scenes.

@see EloquentUser.php

BUT there is HOPE! ...

Paginator->load uses a magic method to call the load method on the model collection.

@see ScoutUser.php

<?php
namespace App;
use Illuminate\Pagination\LengthAwarePaginator;
use App\Http\Controllers\Controller;
class EloquentUser extends Controller {
// these will work for eloquent, but not with a scout->search since scout is not building a query.
public function paginate($query)
{
/** @var LengthAwarePaginator $posts */
$posts = User::with('posts')->paginate(10);
// or
$posts = $this->user->with('posts')->paginate(10);
return $posts;
}
}
<?php
namespace App;
use App\Http\Controllers\Controller;
use Illuminate\Pagination\LengthAwarePaginator;
class ScoutUser extends Controller {
public function paginate($query)
{
/** @var LengthAwarePaginator $paginatedResults */
$paginatedResults = User::search($query)->paginate(25);
/** @var User[] $modelCollection */
/*$modelCollection = */ $paginatedResults->load('dealer');
// LengthAwarePaginator->load calls load on the "items" within the paginator
// it @returns a collection, but also updates the Paginator items
// do not use the return value, continue to use the Paginator $paginatedResults
return $paginatedResults;
}
}
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Laravel\Scout\Searchable;
class User extends Authenticatable
{
use Searchable, Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
}
@pierrocknroll
Copy link

Thanks for this !

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment