Skip to content

Instantly share code, notes, and snippets.

@maynagashev
Created November 9, 2017 11:27
Show Gist options
  • Save maynagashev/c5db1e5e946e576c62ac1072414636c3 to your computer and use it in GitHub Desktop.
Save maynagashev/c5db1e5e946e576c62ac1072414636c3 to your computer and use it in GitHub Desktop.
Laravel slug mutator (most basic implementation)
<?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