Skip to content

Commit

Permalink
initial
Browse files Browse the repository at this point in the history
  • Loading branch information
filipac committed Sep 15, 2014
0 parents commit 2de9a38
Show file tree
Hide file tree
Showing 5 changed files with 249 additions and 0 deletions.
21 changes: 21 additions & 0 deletions LICENSE.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
The MIT License (MIT)

Copyright (c) 2014 Filip Pacurar

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
104 changes: 104 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
Searchable, a search trait for Laravel
==========================================

Searchable is a trait for Laravel 4.2+ that adds a simple search function to Eloquent Models.

Searchable allows custom columns and relevance for each model.

# Installation

Simply add the package to your `composer.json` file and run `composer update`.

```
"filipac/searchable": "1.0.*"
```

## Usage

Add the trait to your model and your search rules.

```php
use Filipac\Searchable\SearchableTrait;

class User extends \Eloquent
{
use SearchableTrait;

/**
* Searchable rules.
*
* @var array
*/
protected $searchable = [
['column' => 'first_name', 'relevance' => 10],
['column' => 'last_name', 'relevance' => 10],
['column' => 'bio', 'relevance' => 2],
['column' => 'email', 'relevance' => 5],
];
}
```

Now you can search your model.

```php
// Simple search
$users = User::search($query)->get();

// Search and get relations
$users = User::search($query)
->with('photos')
->get();
```


## Search Paginated

Laravel default pagination doesn't work with this, you have to do it this way

```php
// This class is required
use Filipac\Searchable\DBHelper;
```

```php
// Get the current page values
$page = Input::get('page') ? Input::get('page') : 1;
$count = Input::get('count') ? Input::get('count') : 20; // items per page
$from = 1 + $count * ($page - 1);

// Perform the search
$data = User::search($query)
->take($count)
->skip($from - 1)
->get()
->toArray();

// Get the count of rows of the last query
$db_query_log = DB::getQueryLog();
$db_query = end($db_query_log);
$total_items = DBHelper::getQueryCount($db_query);

// Create the paginator
$users = Paginator::make($data, $total_items, $count);
```

If you want to search through relations too, you can add the following to the desired model:

```
protected $joinable = [
'profiles' => ['users.profile_id','profiles.id']
];
```
The code above would join the the ```profiles``` table on ```users.profile_id = profiles.id```. Then you can add the following to search in profiles table:
```
/**
* Searchable rules.
*
* @var array
*/
protected $searchable = [
['column' => 'name', 'relevance' => 10],
['column' => 'profiles.name', 'relevance' => 1],
['column' => 'profiles.description', 'relevance' => 2],
];
```
23 changes: 23 additions & 0 deletions composer.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
{
"name": "filipac/searchable",
"description": "Eloquent model search trait.",
"keywords": ["laravel", "eloquent", "search", "searchable"],
"license": "MIT",
"authors": [
{
"name": "Filip Pacurar",
"email": "[email protected]"
}
],
"require": {
"php": ">=5.4.0",
"illuminate/support": "4.2.x",
"illuminate/database": "4.2.x"
},
"autoload": {
"psr-0": {
"Filipac\\Searchable": "src/"
}
},
"minimum-stability": "stable"
}
23 changes: 23 additions & 0 deletions src/Filipac/Searchable/DBHelper.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<?php namespace Filipac\Searchable;

class DBHelper {
//get the count of rows of a query
//only tested with the search
public static function getQueryCount($db_query)
{
$query = $db_query['query'];
$bindings = $db_query['bindings'];

//we take out the order by and limit, becouse its not necesary
$query = explode(' order by ', $query)[0];
$query = explode(' limit ', $query)[0];

//build the count query
$count_query = 'select count(*) as count from (' . $query . ') as results';

//execute the query and get the result
$count = \DB::select(\DB::raw($count_query), $bindings)[0]->count;

return intval($count);
}
}
78 changes: 78 additions & 0 deletions src/Filipac/Searchable/SearchableTrait.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
<?php namespace Filipac\Searchable;

trait SearchableTrait
{
public function scopeSearch($query, $search)
{
//if no search query just return the simple query
if (!$search) return $query;

$selects = [];

//here we add the if's functions to the selects array
//we separate each word
$words = explode(' ', $search);
//we need to count the sum of relevance to take only the good results
$relevance_count = 0;
for ($i = 0; $i < count($this->searchable); $i++) {
$field = $this->searchable[$i];
$relevance_count += $field['relevance'];
//for each word and column we make a like and a =, the = has more relevance
//first with the =
$equal_fields = [];
foreach ($words as $word) {
$equal_fields[] = $field['column'] . " = '" . $word . "'";
}

//we join each =
$equal_fields = join(' || ', $equal_fields);

//we put the ='s into the if function and set the relevance
//if it match it adds the relevance number to the relevance column
$selects[] = 'if(' . $equal_fields . ', ' . $field['relevance'] * 15 . ', 0)';

//then the like
$like_fields = [];
foreach ($words as $word) {
$like_fields[] = $field['column'] . " LIKE '" . $word . "%'";
}

//we join each like
$like_fields = join(' || ', $like_fields);

//we put the like's into the if function and set the relevance
//if it match it adds the relevance number to the relevance column
$selects[] = 'if(' . $like_fields . ', ' . $field['relevance'] * 5 . ', 0)';

//and then the other like
$like_other_fields = [];
foreach ($words as $word) {
$like_other_fields[] = $field['column'] . " LIKE '%" . $word . "%'";
}

//we join each like
$like_other_fields = join(' || ', $like_other_fields);

//we put the like's into the if function and set the relevance
//if it match it adds the relevance number to the relevance column
$selects[] = 'if(' . $like_other_fields . ', ' . $field['relevance'] . ', 0)';
}

//we sum each match to see the relevance
$selects = \DB::raw(join(' + ', $selects) . ' as relevance');
$query->select(['*', $selects]);

if($this->joinable) {
foreach($this->joinable as $table => $how) {
$query->join($table, $how[0], '=', $how[1]);
}
}

//this make that we only select the matching rows
$query->havingRaw('relevance > ' . ($relevance_count / 4));
//order rows by relevance
$query->orderBy('relevance', 'desc');

return $query;
}
}

0 comments on commit 2de9a38

Please sign in to comment.