Search code examples
phplaraveluuid

Generating Uuid as Primary Key


Please i am having an issue generating a uuid as primary key in my user model. i always PHP Error: Class 'App/Traits/boot' not found in C:/xampp/htdocs/twingle/app/Traits/UsesUuid.php on line 11. Tried various method but this error persist

User Model (App\User)


<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use App\Traits\UsesUuid;

class User extends Authenticatable
{
    use Notifiable,UsesUuid;

    protected $keyType = 'string';

    public $incrementing = false;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

    /**
     * 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',
    ];
}

which use a Trait

UseUuid(App\Traits)

<?php

namespace App\Traits;
use Ramsey\Uuid\Uuid;


trait UsesUuid
{
  public static function UsesUuid()
    {
        boot::creating(function ($model) {
            $model->setAttribute($model->getKeyName(), Uuid::uuid4());
        });
    }
}

User mIgration

    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->uuid('id')->primary();
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });

Please any help will be deeply appreciated. thanks


Solution

  • Your trait code looks really inconsistent. It should look something like this:

    namespace App\Traits;
    use Ramsey\Uuid\Uuid;
    
    
    trait UsesUuid
    {
        protected static function boot()
        {
            parent::boot();
    
            static::creating(function ($model) {
                $model->setAttribute($model->getKeyName(), Uuid::uuid4());
            });
        }
    }
    

    That way when the trait is used in a model, it will automatically hook into that model's creating event, and will make sure the primary key is generated as a UUID.