Scout cannot do a standard relation call because it is not using Eloquent behind the scenes.
@see EloquentUser.php
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', | |
]; | |
} |
Thanks for this !