DanVeira DanVeira - 26 days ago 7
PHP Question

Laravel's Eloquent method getKey() returns the first number of the UUID

I have a

User
and a
Role
model extending Catalyst's Sentinel package.

Everything works fine if I use the default incrementing primary key. When I change it to use UUIDs it acts weird. Everything works fine except for a little detail.

Here's the code snippet to check whether the
User
belongs to a
Role
or not:

public function inRole($role)
{
if ($role instanceof RoleInterface) {
$roleId = $role->getRoleId();
}
foreach ($this->roles as $instance) {
if ($role instanceof RoleInterface) {
if ($instance->getRoleId() === $roleId) {
return true;
}
} else {
if ($instance->getRoleId() == $role || $instance->getRoleSlug() == $role) {
return true;
}
}
}
return false;
}


What that code does is: if I pass an instance of
Role
it loops through all the user's roles and check whether any of them match the provided
$role
's id.

Here's the
$user->roles
(
$this->roles
) relationship:

public function roles()
{
return $this->belongsToMany(static::$rolesModel, 'role_users', 'user_id', 'role_id')->withTimestamps();
}


The
$role->getRoleId()
correctly returns the UUID:
"8fbc99e2-3cbb-4e98-b0e3-4c88027d787f"


But the
$instance->getRoleId()
returns
8
, or whatever the first numeric character of the UUID is. If the first character is a letter then it returns
0
.

I have confirmed that
$instance
is indeed an instance of
RoleInterface
so I think it should behave exactly the same as
$role
.

I have also added
public $incrementing = false
to both models.

I have made several checkpoints across all the vendor functions that are called and I can't figure out why this is happening.

Any help is greatly appreciated.

I have opened a new issue on their GitHub repository so here's the link to keep the answers in sync: github.com/cartalyst/sentinel/issues/289 (sorry, I can't post more than 2 links)

Answer