When user creation, assign role_id with UUID

Viewed 68

I have a UUID system on my application and when I register a user I have to indicate the rank_id, only I don't know its ID as it is generated from a UUID. So I use a query but it seems to me disgusting.

Do you have another solution? I thought about not putting a UUID on the rank table to make it easier but I don't know if it's a good idea to mix uuid and classic id

User::create([
   'rank_id' => Rank::select('id')->where('title', 'User')->first()->id,
   'username' => $request->input('username'),
   'email' => strtolower($request->input('email')),
   'password' => Hash::make($request->input('password')),
]);
Schema::create('users', function (Blueprint $table) {
            $table->uuid('id')->primary();

            $table->foreignUuid('rank_id')->constrained('ranks');

            $table->string('username');
            $table->string('email');
            $table->string('password');
            $table->integer('status')->default(0);

            $table->rememberToken();
            $table->timestamps();
        });
Schema::create('ranks', function (Blueprint $table) {
            $table->uuid('id')->primary();

            $table->string('title');

            $table->timestamps();
        });
1 Answers

For easier access, create a helper class or function and use it.

For example create a directory called app\Helpers and inside create a class called RankHelper. The implementation can be like below:

namespace App\Helpers;

use App\Models\Rank;

class RankHelper
{
    public static function getIdByName(string $name): string
    {
        if (!$rank = Rank::select('id')->where('title', $name)->first()) {
            throw new \Exception("No rank with this name found.");
        }
        
        return $rank->id;
    }
}

Then inside your user creation logic just use it like:

User::create([
   'rank_id'   => RankHelper::getIdByName('User'),
   'username'  => $request->input('username'),
   'email'     => strtolower($request->input('email')),
   'password'  => Hash::make($request->input('password')),
]);

Related