PHP code example of riipandi / laravel-optikey

1. Go to this page and download the library: Download riipandi/laravel-optikey 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/ */

    

riipandi / laravel-optikey example snippets


// If using UUID for the key
$table->uuid('uid')->after('id')->unique()->index();

// If using nanoid or ulid for the key
$table->string('uid')->after('id')->unique()->index();



use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class AddOptikeyToUsersTable extends Migration
{
    public function up()
    {
        // Add uid column to users table
        Schema::table('users', function (Blueprint $table) {
            $table->string('uid', 26)->index()->after('id');
        });

        // Prefill uid column in users table
        Schema::table('users', function (Blueprint $table) {
            $results = DB::table('users')->select('id')->get();
            foreach ($results as $result) {
                $ulid = \Ulid\Ulid::generate($lowercase = true); // Generate new lowercase Ulid
                $generated = 'user_'.$ulid; // this is the generated value with optional prefix
                DB::table('users')->where('id', $result->id)->update(['uid' => $generated]);
            }
        });

        // Set uid column as unique
        Schema::table('users', function (Blueprint $table) {
            $table->unique('uid');
        });
    }

    public function down()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->dropColumn('uid');
        });
    }
}



namespace App;

use Illuminate\Database\Eloquent\Model;
use Riipandi\LaravelOptiKey\Traits\HasNanoidKey;

class User extends Model
{
    use HasNanoidKey;

    protected $optiKeyFieldName = 'uid';   // mandatory (you can change this field name)
    protected $optiKeyLowerCase = true;    // optional (default: false)
    protected $optiKeyPrefix = 'user_';    // optional (default: null)

    ....
}

\App\User::byOptiKey('xxxxxxxxxxx')->first();

\App\User::findByOptiKey('xxxxxxxxxxx');

$table->uuid('id')->primary();         // for UUID
$table->string('id', 26)->primary();   // for Ulid
$table->string('id', 16)->primary();   // for nanoid



namespace App;

use Illuminate\Database\Eloquent\Model;
use Riipandi\LaravelOptiKey\Traits\HasUlidKey;
use Riipandi\LaravelOptiKey\Traits\OptiKeyAsPrimary;

class User extends Model
{
    use HasUlidKey;
    use OptiKeyAsPrimary;

    protected $optiKeyFieldName = 'id';

    ...
}
sh
php artisan make:migration AddOptikeyToUsersTable