Searchable::scopeSearch()   A
last analyzed

Complexity

Conditions 4
Paths 4

Size

Total Lines 19
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 10
c 1
b 0
f 0
nc 4
nop 2
dl 0
loc 19
rs 9.9332
1
<?php
2
3
use Exception;
4
use Illuminate\Database\Eloquent\Builder;
5
use Illuminate\Support\Str;
6
7
trait Searchable
8
{
9
    public function scopeSearch(Builder $builder, string $term = '')
10
    {
11
        if (! $this->searchable) {
12
            throw new Exception('Please define the searchable property . ');
13
        }
14
        foreach ($this->searchable as $searchable) {
15
            if (str_contains($searchable, '.')) {
16
                $relation = Str::beforeLast($searchable, '.');
17
18
                $column = Str::afterLast($searchable, '.');
19
20
                $builder->orWhereRelation($relation, $column, 'like', "%$term%");
21
22
                continue;
23
            }
24
            $builder->orWhere($searchable, 'like', "%$term%");
25
        }
26
27
        return $builder;
28
    }
29
}
30