Created
August 27, 2024 16:26
-
-
Save davutkmbr/fcdb2f7ab2f65e6090e9a52135da3352 to your computer and use it in GitHub Desktop.
Create unique random values for Eloquent Model.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Eloquent\Concerns; | |
use Illuminate\Database\Eloquent\Model; | |
trait HasRandomFields | |
{ | |
public static function bootHasRandomFields() | |
{ | |
static::creating(function (Model $model) { | |
$model->setRandomFields(); | |
}); | |
} | |
public function randomFields(): array | |
{ | |
return []; | |
} | |
public function setRandomFields(): void | |
{ | |
$fields = $this->randomFields(); | |
foreach ($fields as $field => $callback) { | |
if (is_null($this->{$field})) { | |
$this->{$field} = $this->makeUnique($field, $callback); | |
} | |
} | |
} | |
public function makeUnique($field, $callback): string | |
{ | |
$value = $callback(); | |
while ($this->where($field, $value)->exists()) { | |
$value = $callback(); | |
} | |
return $value; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Models; | |
use App\Eloquent\Concerns\HasRandomFields; | |
use Illuminate\Database\Eloquent\Model; | |
class Order extends Model | |
{ | |
use HasFactory, HasRandomFields; | |
protected $fillable = [ | |
'token', | |
// the other fillable fields... | |
]; | |
public function randomFields(): array | |
{ | |
return [ | |
'token' => fn () => Str::random(24), | |
// the other random fields. | |
]; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment