Last active
August 29, 2015 14:27
-
-
Save codegenin/2cbac6a86be1f051b333 to your computer and use it in GitHub Desktop.
Laravel - set a field into a slug on record insert
This file contains hidden or 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 | |
/** | |
* Set name field to slug on insert | |
* | |
* @param $name | |
*/ | |
public function setNameAttribute($name) | |
{ | |
$this->attributes['name'] = $name; | |
if (!$this->exists) { | |
$this->setUniqueSlug($name, ''); | |
} | |
} | |
/** | |
* Recursive routine to set unique slug | |
* | |
* @param $name | |
* @param $extra | |
*/ | |
protected function setUniqueSlug($name, $extra) | |
{ | |
$slug = str_slug($name.'-'.$extra); | |
if (static::whereSlug($slug)->exists()) { | |
$this->setUniqueSlug($name, $extra + 1); | |
return; | |
} | |
$this->attributes['slug'] = $slug; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment