Skip to content

Instantly share code, notes, and snippets.

@novecentonove
Last active June 28, 2021 11:17
Show Gist options
  • Save novecentonove/c39e35df41139a00c746188e7965231b to your computer and use it in GitHub Desktop.
Save novecentonove/c39e35df41139a00c746188e7965231b to your computer and use it in GitHub Desktop.
Generate a Unique Id (short) for Laravel User Model
<?php
namespace App\Models;
use Illuminate\Support\Str;
use Spatie\Permission\Traits\HasRoles;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use HasFactory, Notifiable, HasRoles;
protected $fillable = [
'name',
'email',
'password',
'slug'
];
const SLUGLENGTH = 7;
// SLUG
public function getRouteKeyName(){
return 'slug';
}
private static function createUid($num){
return Str::random($num);
}
protected static function boot()
{
parent::boot();
// auto-sets values on creation
static::creating(function ($user) {
$uniqid = static::createUid(self::SLUGLENGTH);
do {
$uniqid = static::createUid(self::SLUGLENGTH);
}
while ($uniqid == self::where('slug', $uniqid)->exists());
$user->slug = $uniqid;
});
}
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment