PHP code example of your-app-rocks / eloquent-uuid

1. Go to this page and download the library: Download your-app-rocks/eloquent-uuid library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

your-app-rocks / eloquent-uuid example snippets




Schema::create('users', function (Blueprint $table) {
    $table->uuid('uuid');
    $table->string('name');
    $table->timestamps();
});



namespace App\YourNameSpace;

use Illuminate\Database\Eloquent\Model;
use YourAppRocks\EloquentUuid\Traits\HasUuid;

class User extends Model
{
    use HasUuid;
}



namespace App\YourNameSpace;

use App\YourNameSpace\User;
use Illuminate\Http\Request;

class UserController extends Controller
{

    /**
     * When a new record is inserted into the table `(with the create() or save() methods)`,
     * Trait "HasUuid" will automatically generate a uuid version 4* for the 'uuid' column of your schema.
     */
    public function store(Request $request)
    {
        $user = User::create($request->all()); // Automatically generate a uuid

        return $user->getUuid() // Return UUID value.
    }

    /**
     * Get User by custom 'UUID' key name - Implicit Binding.
     * See https://laravel.com/docs/5.8/routing#route-model-binding
     *
     * @param User $user
     * @return void
     */
    public function show(User $user)
    {
        return $user;
    }

    //OR

    /**
     * Get User by scope query.
     */
    public function show($uuid)
    {
        $user = User::findByUuid($uuid);

        return $user;
    }
}



//Create table
Schema::create('posts', function (Blueprint $table) {
    $table->uuid('universally_unique_id');
    $table->string('title');
    $table->timestamps();
});

//Eloquent Model
class Post extends Model
{
    use HasUuid;

    protected $uuidColumnName = 'universally_unique_id';
    protected $uuidVersion = 1;    // Available 1,3,4 or 5
    protected $uuidString  = '';   // Needed when $uuidVersion is "3 or 5"
}



//Create table
Schema::create('users', function (Blueprint $table) {
    $table->uuid('uuid');
    $table->string('name');
    $table->timestamps();
});

//Create MyUuidTrait with custom code
use YourAppRocks\EloquentUuid\Traits\Uuidable;

trait MyUuidTrait
{
    use Uuidable;

    /**
     * Boot trait on the model.
     *
     * @return void
     */
    public static function bootMyUuidTrait()
    {
        static::creating(function ($model) {
            // My custom code here.
        });

        static::saving(function ($model) {
            // My custom code here.
        });
    }

    // My custom code here.
}

//Create Model
use MyUuidTrait;
use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    use MyUuidTrait;
}