You just need to change your toSearchableArray
method from your model by adding the following code:
/**
* Get the indexable data array for the model.
*
* @return array
*/
public function toSearchableArray()
{
$array = $this->only('title', 'description');
$related = $this->user->only('name', 'email');
// Customize array...
return array_merge($array, $related);
}
Then call php artisan scout:import "App\YourModel"
to reindex the new records.
Note:
$this->only('title', 'description')
will search only for its title and description fields
$this->user->only('name', 'email')
will also search for its name and email from a related Model
So you can retrieve the related data by adding ->load('user')
in your search method like the following code:
public function search(Request $request)
{
$query = $request->get('q');
return Task::search($query)->get()->load('user');
}
UPDATE
If you're trying to retrieve the data using ->paginate() method, you must need to load the relations separately:
...
$tasks = Task::search($query)->paginate($request->get('per_page'));
$tasks->load('user');
return $tasks;
Enjoy!
array_merge()
will fail. The var$related
is not an array by itself, needs to be like$related->all()
to return an array. – Mahmoud