Skip to content

Builder searchable and more

Jarek Tkaczyk edited this page May 14, 2015 · 7 revisions

Eloquence\Builder

Eloquence Builder ships with a few addons to the base eloquent query builder. The most significant is Searchable feature.

Searchable

tldr; You can easily search through any columns on the model's table or any of its relations (no-matter-how-deeply-nested) and return the result sorted by search relevance (with possible weight for each column).

Let's see it in action:

<?php namespace App;

use Sofa\Eloquence\Eloquence;
use Illuminate\Database\Eloquent\Model;

class User extends Model
{
   use Eloquence;

   // no need for this, but you can define default searchable columns:
   protected $searchableColumns = ['name', 'email'];

   // let's add some relations
   public function profile()
   {
      return $this->belongsTo(Profile::class); // also Profile belongsTo Address
   }

   public function posts()
   {
      return $this->hasMany(Post::class); // also Post belongsToMany Categories
   }
}

Then we can do this:

// basic usage, fulltext search for '*jarek*' or '*sofa*' thru defined columns
>>> User::search('jarek sofa')->get()

// exact search for 'jarek tkaczyk' thru defined columns
>>> User::search('"jarek tkaczyk"', false)->first()

// wildcard search for 'jarek*' or '*czyk' thru provided columns with weighted score
>>> User::search(['jarek*', '*czyk'], ['name' => 10, 'email' => 5], false)->get()

// fulltext search on multiple tables (joined automatically using dot nested relations)
>>> User::search('foo bar', ['name', 'posts.title', 'posts.categories.name', 'profile.address.city'])->get()

Searchable feature is based on great https://github.com/nicolaslopezj/searchable trait, only it's more than 4 times faster and gives you huge flexibility - pretty much everything is done for you under the hood.

...

Clone this wiki locally