Skip to content

Instantly share code, notes, and snippets.

@nicoaudy
Forked from mul14/README.md
Created February 16, 2021 06:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nicoaudy/70c16e859e38e39a0ae292f383b7e173 to your computer and use it in GitHub Desktop.
Save nicoaudy/70c16e859e38e39a0ae292f383b7e173 to your computer and use it in GitHub Desktop.
Simple Laravel Search Trait

Usage

Put SearchTrait.php in app directory. Then use SearchTrait in your model, like so

use App\SearchTrait;
use Illuminate\Database\Eloquent\Model;

class Article extends Model 
{
    use SearchTrait; // Add this
    
    // Optional properties
    protected $search = ['title', 'content'];

}

Somewhere in your controller

$keyword = 'lorem';

// Match any fields
Article::search($keyword)->paginate();

// Match all fields
Article::search($keyword, true)->paginate();
<?php
namespace App;
use Illuminate\Support\Facades\Schema;
trait SearchTrait
{
/**
* @param \Illuminate\Database\Eloquent\Builder|static $query
* @param string $keyword
* @param boolean $matchAllFields
*/
public static function scopeSearch($query, $keyword, $matchAllFields = false)
{
return static::where(function ($query) use ($keyword, $matchAllFields) {
foreach (static::getSearchFields() as $field) {
if ($matchAllFields) {
$query->where($field, 'LIKE', "%$keyword%");
} else {
$query->orWhere($field, 'LIKE', "%$keyword%");
}
}
});
}
/**
* Get all searchable fields
*
* @return array
*/
public static function getSearchFields()
{
$model = new static;
$fields = $model->search;
if (empty($fields)) {
$fields = Schema::getColumnListing($model->getTable());
$others[] = $model->primaryKey;
$others[] = $model->getUpdatedAtColumn() ?: 'created_at';
$others[] = $model->getCreatedAtColumn() ?: 'updated_at';
$others[] = method_exists($model, 'getDeletedAtColumn')
? $model->getDeletedAtColumn()
: 'deleted_at';
$fields = array_diff($fields, $model->getHidden(), $others);
}
return $fields;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment