|
1
|
|
|
<?php namespace Cviebrock\EloquentSluggable; |
|
2
|
|
|
|
|
3
|
|
|
/** |
|
4
|
|
|
* Class PrimarySlug |
|
5
|
|
|
* |
|
6
|
|
|
* Helper trait for defining the primary slug of a model |
|
7
|
|
|
* and providing useful scopes and query methods. |
|
8
|
|
|
* |
|
9
|
|
|
* @package Cviebrock\EloquentSluggable |
|
10
|
|
|
*/ |
|
11
|
|
|
trait SluggableScopeHelpers |
|
12
|
|
|
{ |
|
13
|
|
|
|
|
14
|
|
|
/** |
|
15
|
|
|
* Primary slug column of this model. |
|
16
|
|
|
* |
|
17
|
|
|
* @return string |
|
18
|
|
|
*/ |
|
19
|
|
|
public function getSlugKeyName() |
|
20
|
|
|
{ |
|
21
|
|
|
if (property_exists($this, 'slugKeyName')) { |
|
22
|
|
|
return $this->slugKeyName; |
|
|
|
|
|
|
23
|
|
|
} |
|
24
|
|
|
|
|
25
|
|
|
$keys = array_keys($this->sluggable()); |
|
|
|
|
|
|
26
|
|
|
|
|
27
|
|
|
return reset($keys); |
|
28
|
|
|
} |
|
29
|
|
|
|
|
30
|
|
|
/** |
|
31
|
|
|
* Primary slug value of this model. |
|
32
|
|
|
* |
|
33
|
|
|
* @return string |
|
34
|
|
|
*/ |
|
35
|
|
|
public function getSlugKey() |
|
36
|
|
|
{ |
|
37
|
|
|
return $this->getAttribute($this->getSlugKeyName()); |
|
|
|
|
|
|
38
|
|
|
} |
|
39
|
|
|
|
|
40
|
|
|
/** |
|
41
|
|
|
* Query scope for finding a model by its primary slug. |
|
42
|
|
|
* |
|
43
|
|
|
* @param \Illuminate\Database\Eloquent\Builder $scope |
|
44
|
|
|
* @param string $slug |
|
45
|
|
|
* @return \Illuminate\Database\Eloquent\Builder |
|
46
|
|
|
*/ |
|
47
|
|
|
public function scopeWhereSlug($scope, $slug) |
|
48
|
|
|
{ |
|
49
|
|
|
return $scope->where($this->getSlugKeyName(), $slug); |
|
50
|
|
|
} |
|
51
|
|
|
|
|
52
|
|
|
/** |
|
53
|
|
|
* Find a model by its primary slug. |
|
54
|
|
|
* |
|
55
|
|
|
* @param string $slug |
|
56
|
|
|
* @param array $columns |
|
57
|
|
|
* @return \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Collection|static[]|static|null |
|
58
|
|
|
*/ |
|
59
|
|
|
public static function findBySlug($slug, array $columns = ['*']) |
|
60
|
|
|
{ |
|
61
|
|
|
return static::whereSlug($slug)->first($columns); |
|
|
|
|
|
|
62
|
|
|
} |
|
63
|
|
|
|
|
64
|
|
|
/** |
|
65
|
|
|
* Find a model by its primary slug or throw an exception. |
|
66
|
|
|
* |
|
67
|
|
|
* @param string $slug |
|
68
|
|
|
* @param array $columns |
|
69
|
|
|
* @return \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Collection |
|
70
|
|
|
* |
|
71
|
|
|
* @throws \Illuminate\Database\Eloquent\ModelNotFoundException |
|
72
|
|
|
*/ |
|
73
|
|
|
public static function findBySlugOrFail($slug, array $columns = ['*']) |
|
74
|
|
|
{ |
|
75
|
|
|
return static::whereSlug($slug)->firstOrFail($columns); |
|
|
|
|
|
|
76
|
|
|
} |
|
77
|
|
|
} |
|
78
|
|
|
|
In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:
Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion: