Romanovich095

Untitled

Jul 4th, 2018
139
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 0.98 KB | None | 0 0
  1. <?php
  2. /**
  3.  * Created by PhpStorm.
  4.  * User: roman-kozin
  5.  * Date: 03.07.18
  6.  * Time: 12:31
  7.  */
  8.  
  9. namespace App\Traits;
  10.  
  11.  
  12. use Illuminate\Database\Eloquent\Builder;
  13. use Illuminate\Database\Eloquent\Model;
  14.  
  15. /**
  16.  * Trait Search
  17.  * @package App\Traits
  18.  * @property array searchFields
  19.  */
  20. trait Search
  21. {
  22.  
  23.     protected $searchFields = ['title', 'title_en', 'Taggs', 'Taggs_en'];
  24.  
  25.     /**
  26.      * @param Model|Builder $model
  27.      * @param null $q
  28.      * @param array $noFields
  29.      * @return array
  30.      */
  31.     public function findForSearch($model, $q = null, $noFields = [])
  32.     {
  33.  
  34.         if ($noFields) {
  35.             $this->searchFields = array_diff($this->searchFields, $noFields);
  36.         }
  37.  
  38.         foreach ($this->searchFields as $i => $searchField) {
  39.             $model = !$i
  40.                 ? $model->where($searchField, 'like', "%{$q}%") :
  41.                 $model->orWhere($searchField, 'like', "%{$q}%");
  42.         }
  43.  
  44.         return $model->get()->toArray();
  45.     }
  46. }
Advertisement
Add Comment
Please, Sign In to add comment