This is a simple trait for database searching.
Our model should of course use the Searchable trait. Likewise, we have to declare the model attributes which shall be searchable.
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\Traits\Searchable;
class User extends Model
{
use Searchable;
/**
* The attributes that are searchable.
*
* @var array
*/
protected $searchable = [
'name',
'email',
];
}
We could also make relationships' attributes searchable:
/**
* The attributes that are searchable.
*
* @var array
*/
protected $searchable = [
'name',
'email',
'posts' => [
'title',
'text'
],
'posts.comments' => [
'title',
'text',
],
];
To query the model we have few options after passing the search term as the first argument:
return User::search('john')->paginate(15);
Here, the attributes defined in the model and attributes passed in the second argument will be queried:
return User::search('john', ['username', 'email'])->paginate(15);
Here, attributes passed in the second argument will be queried and the attributes defined in the model will be ignored:
return User::search('john', ['username', 'email'], false)->paginate(15);
Model relations can be passed as follows:
return User::search('john', [
'email',
'posts' => [
'title',
'text'
],
'posts.comments' => [
'title',
'text',
]])->get();