Why on earth would you need to do that?
How use negative integer as primary key
Hello,
For some reasons that I have a table which can be populated by a desktop application and a laravel application, I need to use negative integer as primary key for some tables. So I can't use auto-increment for theses tables on Laravel. Do you have any idea of which is the best solution to do this and if it's ok for Laravel to work with negative primary key ?
Regards
@FabienArr There are two ways:
- examine
\Illuminate\Database\Eloquent\Concerns\HasUuidstrait in Laravel source code and create your own:
trait HasUuidsWithoutDashes
{
use HasUniqueStringIds;
public function newUniqueId()
{
return (string) Str::of(Str::uuid7())->remove('-');
}
}
Attach use HasUuidsWithoutDashes; to your model instead of HasUuids.
Note that HasUuids trait has isValidUniqueId() method which is not applicable to your situation (UUID without dashes is not valid UUID for Laravel, as function Str::isUuid($uuid_without_dashes) results in false). I don't know how it affects your app. Maybe you should implement it too:
protected function returnDashes(string $value): string
{
// in: 019889e6ad48710f9305772d4cd1a0c1
// out: 019889e6-ad48-710f-9305-772d4cd1a0c1
$value = Str::of($value);
return sprintf('%s-%s-%s-%s-%s',
$value->substr(0, 8),
$value->substr(8, 4),
$value->substr(12, 4),
$value->substr(16, 4),
$value->substr(20, 12),
);
}
protected function isValidUniqueId($value): bool
{
return Str::isUuid($this->returnDashes($value));
}
- Second approach is to create cast which removes dashes on
setand adds them ongetand apply it to your models' UUID fields: https://laravel.com/docs/12.x/eloquent-mutators#custom-casts
Both ways are non-standard, you should test them carefully.
Please or to participate in this conversation.