Created
November 9, 2017 11:27
-
-
Save maynagashev/c5db1e5e946e576c62ac1072414636c3 to your computer and use it in GitHub Desktop.
Laravel slug mutator (most basic implementation)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
use Illuminate\Database\Eloquent\Model; | |
class ModelWithSlug extends Model | |
{ | |
public function setSlugAttribute($val) | |
{ | |
$val = trim($val); | |
$val = str_slug($val); | |
// check empty (fallback with title) | |
if ($val == '') { | |
$val = str_slug($this->title); | |
} | |
// check unique (fallback with uniqid suffix) | |
$duplicate = ModelWithSlug::whereSlug($val)->where('id', '<>', $this->id)->first(); | |
if ($duplicate) { | |
$val = $val.uniqid(); | |
} | |
// mutate | |
$this->attributes['slug'] = $val; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment