Skip to content

Instantly share code, notes, and snippets.

@ulhaq
Last active July 30, 2020 03:47
Show Gist options
  • Save ulhaq/2c72b9ca6ec691aef6f11e32e55e07b3 to your computer and use it in GitHub Desktop.
Save ulhaq/2c72b9ca6ec691aef6f11e32e55e07b3 to your computer and use it in GitHub Desktop.
Simple Laravel Database Search

This is a simple trait for database searching.

Model

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',
    ],
];

Controller

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();
<?php
namespace App\Traits;
trait Searchable
{
public function scopeSearch($query, $q, array $columns = [], $push = true)
{
if (!empty($q)) {
if (empty($columns)) {
$columns = $this->searchable;
} else {
if ($push) {
$columns = array_merge_recursive($this->searchable, $columns);
}
}
foreach ($columns as $relation => $column) {
if (is_array($column)) {
foreach ($column as $val) {
$query->orWhereHas($relation, function ($query) use ($q, $val) {
$query->where($val, 'like', "%$q%");
});
}
} else {
$query->orWhere($column, 'like', "%$q%");
}
}
}
return $query;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment