Laravel 8 use uuid as primary key is the todays tutorial. We all know that id
is the default primary key in Laravel. But in this how to use uuid in laravel 8 example, we will create our custom primary key using uuid.
If you don't know how to use uuid in laravel 8 then this will be the perfect tutorial that what are you looking for. So in this laravel 8 uuid primary key tutorial, you will learn it from step by step.
We only need some steps to change your Model to use UUID
as default primary key. Let's see the example code:
App\Traits\Uuid.php
namespace App\Traits;
use Illuminate\Support\Str;
trait Uuid
{
protected static function boot()
{
parent::boot();
static::creating(function ($model) {
try {
$model->id = (string) Str::uuid(); // generate uuid
// Change id with your primary key
} catch (UnsatisfiedDependencyException $e) {
abort(500, $e->getMessage());
}
});
}
}
Now we have use this trait in your model where you want uuid as primary key. So see the code to understand:
App\Models\User.php
namespace App;
use App\Traits\Uuid;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable
{
Use Uuid, Notifiable;
public $incrementing = false;
protected $keyType = 'uuid';
}
Now use in your migration like below:
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->uuid('id')->primary();
// another column
});
}
Read also : When and How to Use @class Blade Directive in Laravel
Hope it can help you.
#laravel #laravel-8x #uuid