Add UUID (or swap bigIncrement) and make sure to set as primary column:
Schema::create('events', function (Blueprint $table) {
$table->uuid('id')->primary();
When using the column as a foreign key in a pivot table, create a UUID column and do the same foreign key assignment:
$table->uuid('organizer_id');
$table->foreign('organizer_id')->references('id')->on('users')->onDelete('cascade');
- Create a trait to add to models:
app/Traits/Uuids.php
<?php
namespace App\Traits;
trait Uuids
{
/**
* Boot function from laravel.
*/
protected static function boot()
{
parent::boot();
static::creating(function ($model) {
$model->{$model->getKeyName()} = (string) \Illuminate\Support\Str::uuid();
});
}
}
Then "use" that trait in your model:
app/Events.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\Traits\Uuids;
class Events extends Model
{
/**
* Generates and inserts uuid when creating new items
*/
use Uuids;
}
- Cast UUID as string inside model (or you'll get errors from foreign keys failing, or UUIDs cast as tiny integers that resemble classic IDs). Reference
app/YourModel.php
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'id' => 'string',
];
Hi mate, thx for this, but can u help me with laravel 9 ? ive tried the same way, and trying to find anytinh on google but still got nothing, i alread make question here if you want to see the detail, [How to use foreignUuid in laravel 9]
thank youu..