fomvasss /
laravel-url-aliases
| 1 | <?php |
||
| 2 | |||
| 3 | namespace Fomvasss\UrlAliases\Models; |
||
| 4 | |||
| 5 | use Illuminate\Database\Eloquent\Model; |
||
| 6 | |||
| 7 | class UrlAlias extends Model |
||
| 8 | { |
||
| 9 | public $timestamps = false; |
||
| 10 | |||
| 11 | protected $guarded = ['id']; |
||
| 12 | |||
| 13 | protected static function boot() |
||
| 14 | { |
||
| 15 | static::creating(function (Model $model) { |
||
| 16 | if (! $model->locale) { |
||
| 17 | $model->locale = app()->app['config']->get('app.locale'); |
||
|
0 ignored issues
–
show
Bug
introduced
by
Loading history...
|
|||
| 18 | } |
||
| 19 | }); |
||
| 20 | |||
| 21 | parent::boot(); |
||
| 22 | } |
||
| 23 | |||
| 24 | /** |
||
| 25 | * @return string |
||
| 26 | */ |
||
| 27 | public function getLocaleAliasAttribute() |
||
| 28 | { |
||
| 29 | if (is_url($this->attributes['alias']) || $this->attributes['locale'] == $this->attributes['alias']) { |
||
| 30 | return $this->attributes['alias']; |
||
| 31 | } |
||
| 32 | |||
| 33 | return $this->attributes['locale'] . '/' . $this->attributes['alias']; |
||
| 34 | } |
||
| 35 | |||
| 36 | /** |
||
| 37 | * @return string |
||
| 38 | */ |
||
| 39 | public function getLocaleSourceAttribute() |
||
| 40 | { |
||
| 41 | if (is_url($this->attributes['source']) || $this->attributes['locale'] == $this->attributes['alias']) { |
||
| 42 | return $this->attributes['source']; |
||
| 43 | } |
||
| 44 | return $this->attributes['locale'] . '/' . $this->attributes['source']; |
||
| 45 | } |
||
| 46 | |||
| 47 | /** |
||
| 48 | * @param $query |
||
| 49 | * @param $path |
||
| 50 | * @return mixed |
||
| 51 | */ |
||
| 52 | public function scopeByPath($query, $path) |
||
| 53 | { |
||
| 54 | return $query->where(function($q) use ($path) { |
||
| 55 | $q->where('source', $path)->orWhere('alias', $path); |
||
| 56 | }); |
||
| 57 | } |
||
| 58 | |||
| 59 | /** |
||
| 60 | * @param $value |
||
| 61 | */ |
||
| 62 | public function setAliasAttribute($value) |
||
| 63 | { |
||
| 64 | $this->attributes['alias'] = $value == '/' ? $value : trim($value, '/'); |
||
| 65 | } |
||
| 66 | |||
| 67 | /** |
||
| 68 | * @param $value |
||
| 69 | */ |
||
| 70 | public function setSourceAttribute($value) |
||
| 71 | { |
||
| 72 | $this->attributes['source'] = $value == '/' ? $value : trim($value, '/'); |
||
| 73 | } |
||
| 74 | |||
| 75 | /** |
||
| 76 | * @return \Illuminate\Database\Eloquent\Relations\MorphTo |
||
| 77 | */ |
||
| 78 | public function aliasable() |
||
| 79 | { |
||
| 80 | return $this->morphTo('aliasable', 'model_type', 'model_id'); |
||
| 81 | } |
||
| 82 | } |
||
| 83 |