Create Reusable Trait To Generate And Save Uuid In Laravel

Hello Artisan,

In this tutorial, I am going to show you Laravel tips that how we can automatically generate and save UUID in Laravel 9. In this tutorial, I will create a trait and with this trait, we will generate and save UUID in Laravel.

If any model has a UUID field then we just use that trait. This is going to be our reusable trait to create and save UUID. So just follow the below example to know how to generate UUID laravel 9 and save it into the database.


Step 1: Create Trait

In this step, we will create a HasUuid trait and use them in the model to generate and save uuid. So create it like:


namespace App\Common;

use Illuminate\Support\Str;

trait HasUuid
    public static function bootHasUUID() : void
           $model->uuid = Str::uuid()->toString();


Now assume our User model has uuid column, we have to just use this trait in the User model like below:


namespace App\Models;

use App\Common\HasUuid;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
    use HasUuid;


Recommended: Laravel 9 Use uuid as Primary Key Example


Hope it can help you.


#laravel #laravel-9x #laravel-tips