Skip to content

Instantly share code, notes, and snippets.

@mul14
Last active February 10, 2023 00:55
Show Gist options
  • Save mul14/726c4d2514c5d9f28b43 to your computer and use it in GitHub Desktop.
Save mul14/726c4d2514c5d9f28b43 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
* @return \Illuminate\Database\Eloquent\Builder
*/
public static function scopeSearch($query, $keyword, $matchAllFields = false)
{
return static::where(function ($query) use ($keyword, $matchAllFields) {
foreach (static::getSearchableFields() as $field) {
if ($matchAllFields) {
$query->where($field, 'LIKE', "%$keyword%");
} else {
$query->orWhere($field, 'LIKE', "%$keyword%");
}
}
});
}
/**
* Get all searchable fields
*
* @return array
*/
public static function getSearchableFields()
{
$model = new static;
$fields = $model->search;
if (empty($fields)) {
$fields = Schema::getColumnListing($model->getTable());
$ignoredColumns = [
$model->getKeyName(),
$model->getUpdatedAtColumn(),
$model->getCreatedAtColumn(),
];
if (method_exists($model, 'getDeletedAtColumn')) {
$ignoredColumns[] = $model->getDeletedAtColumn();
}
$fields = array_diff($fields, $model->getHidden(), $ignoredColumns);
}
return $fields;
}
}
@saber13812002
Copy link

great. useful. more helpful than 30 minutes cbt clips

i think this is new great idea for developers... instead of hours of video in youtube. we can read it more rapid

@Ir001
Copy link

Ir001 commented Nov 19, 2020

Mantap, sangat memudahkan

@klisica
Copy link

klisica commented Nov 29, 2020

Any idea on how to extend this trait to handle search on relationships? I.e. on belongsTo relationship

@shreekrishnalamichhane
Copy link

Thanks for sharing this..

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment