Skip to content

Instantly share code, notes, and snippets.

@codegenin
Last active August 29, 2015 14:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save codegenin/2cbac6a86be1f051b333 to your computer and use it in GitHub Desktop.
Save codegenin/2cbac6a86be1f051b333 to your computer and use it in GitHub Desktop.
Laravel - set a field into a slug on record insert
<?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