Little code snippet inspired by Freek and others. Most likely, almost a copy of their implementation. I'm using this a lot in recent projects, so I'd like to keep it easily accessible.
Scope supports:
- searching using relations
- (optional) breaking the word by space and matching to all parts
- for each field defined in
$searchable
attribute scope will addLIKE
query - fields are joined using
orWhere
- if there's a match in at least one field, the model will be fetched - you can add relations to the
$searchable
-
copy the
Search.php
file toapp/Models/Scopes/
-
add the trait to the model:
<?php namespace App\Models; class Foo extends \Illuminate\Database\Eloquent\Model { use Scopes\Search; }
-
define
$searchable
private attributes with list of fields used in searchprotected $searchable = ['name', 'email'];
-
(optional) set custom options
protected $searchOptions = ['break_words' => true];