Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR PHP

how to use uuid in laravel model

1) Implement Uuid trait.

// app/Traits/Uuid.php 
<?php

namespace AppTraits;

use Exception;
use IlluminateDatabaseEloquentModel;
use IlluminateSupportStr;

trait Uuid
{
    protected static function boot()
    {
        parent::boot();

        static::creating(function (Model $model) {
            try {
                $model->id = Str::uuid()->toString();
            } catch (Exception $e) {
                abort(500, $e->getMessage());
            }
        });
    }
}

2) Go to the model class and set $incrementing to false;

// app/Models/*.php
class Whatever implements Model {
	public $incrementing = false;
  	...
}

3) Go to the migration class and set uuid as primary key;
// database/migrations/*.php
class CreateWhateverTable extends Migration {
	public function up()
  	{
      Schema::create("whatever", function (Blueprint $table) {
          // You can change "id" to "uuid" or whatever...	  
          $table->uuid("id")->primary();
          // another column
      });
  	}
}
Source by laravel.com #
 
PREVIOUS NEXT
Tagged: #uuid #laravel #model
ADD COMMENT
Topic
Name
1+1 =