1
|
|
|
<?php namespace Cviebrock\EloquentSluggable; |
2
|
|
|
|
3
|
|
|
use Illuminate\Database\Eloquent\Builder; |
4
|
|
|
|
5
|
|
|
trait FindBySlug |
6
|
|
|
{ |
7
|
|
|
public function scopeWhereOneOfMySlugs(Builder $query, $slug, $fields = []) |
8
|
|
|
{ |
9
|
|
|
$fields = $this->slugFieldsGuard($query, $fields); |
10
|
|
|
|
11
|
|
|
return $query->where(function ($q) use ($slug, $fields) { |
12
|
|
|
foreach ($fields as $column) { |
13
|
|
|
$q->orWhere($column, $slug); |
14
|
|
|
} |
15
|
|
|
}); |
16
|
|
|
} |
17
|
|
|
|
18
|
|
|
public static function findBySlug($slug, $fields = []) |
19
|
|
|
{ |
20
|
|
|
return static::whereOneOfMySlugs($slug, $fields)->first(); |
|
|
|
|
21
|
|
|
} |
22
|
|
|
|
23
|
|
|
public static function findBySlugOrFail($slug, $fields = []) |
24
|
|
|
{ |
25
|
|
|
return static::whereOneOfMySlugs($slug, $fields)->firstOrFail(); |
|
|
|
|
26
|
|
|
} |
27
|
|
|
|
28
|
|
|
public static function findBySlugOrId($slugOrId, $fields = []) |
29
|
|
|
{ |
30
|
|
|
$found = is_numeric($slugOrId) ? static::find($slugOrId) : null; |
31
|
|
|
|
32
|
|
|
return ! is_null($found) ? $found: static::whereOneOfMySlugs($slugOrId, $fields)->first(); |
|
|
|
|
33
|
|
|
} |
34
|
|
|
|
35
|
|
|
public static function findBySlugOrIdOrFail($slugOrId, $fields = []) |
36
|
|
|
{ |
37
|
|
|
$found = is_numeric($slugOrId) ? static::find($slugOrId) : null; |
38
|
|
|
|
39
|
|
|
return ! is_null($found) ? $found : static::whereOneOfMySlugs($slugOrId, $fields)->firstOrFail(); |
|
|
|
|
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
protected function slugFieldsGuard(Builder $query, $fields = []) |
43
|
|
|
{ |
44
|
|
|
$availableSlugFields = array_keys($query->getModel()->sluggable()); |
45
|
|
|
$fields = (array) $fields; |
46
|
|
|
|
47
|
|
|
if (empty($fields)) { |
48
|
|
|
return empty($this->findBySlugDefault()) ? $availableSlugFields: $this->findBySlugDefault(); |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
if (! empty($diff = array_diff($fields, $availableSlugFields))) { |
52
|
|
|
throw new \InvalidArgumentException('Invalid slugs field(s) ' . implode(', ', $diff)); |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
return $fields; |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
protected function findBySlugDefault() |
59
|
|
|
{ |
60
|
|
|
return []; |
61
|
|
|
} |
62
|
|
|
} |
63
|
|
|
|
This check marks calls to methods that do not seem to exist on an object.
This is most likely the result of a method being renamed without all references to it being renamed likewise.