Hi. Im not sure if that is possible, or what is the best way. I want to create a table where the models get hash_ids. I want to do it similar to youtube where domain is not /23 (ID=23) it should be something like /uHN35Dc (ID = 23 but hashed). I use https://hashids.org/php/. But I want to do it while creating process, that the field must not be nullable in migration file. Something like that:
public static function boot() {
parent::boot();
static::creating(function ($item) {
$item->hash_id = 'sD35Dd';
});
}
Is it possible, or should i use null and then do it in created method, when id is already created? Or is there a better way?
You can use the creating method to generate the hash_id when creating the model. The code you provided is a good starting point. You can use the Hashids library to generate the hash_id.
public static function boot() {
parent::boot();
static::creating(function ($item) {
$hashids = new Hashids\Hashids();
$item->hash_id = $hashids->encode($item->id);
});
}
You can also use the created method to generate the hash_id if you don't want to make the field nullable in the migration file.
public static function boot() {
parent::boot();
static::created(function ($item) {
$hashids = new Hashids\Hashids();
$item->hash_id = $hashids->encode($item->id);
$item->save();
});
}
@Sinnbeck I think we dont talk about the same. I talk about the model. There are these static functions. And to generate a hash from ID I need the ID. I wanted to do it in creating, but I think the ID is not created at the time. In created i get the ID from $item->id. The package Hashids is ok and I work with it in the past a lot. But I thought there is a way to get next ID (or id whcih will be created) before creating in the creating method. Or do you mean this laravel static functions in the model is AI?
But no there isn't a way to know the next id without locking the database. Personally I would prefer 2 queries vs locking. Or you could simply not save the hash at all and calculate it on the fly