Skip to content

Instantly share code, notes, and snippets.

@rogercbe
Last active May 14, 2018 12:05
Show Gist options
  • Select an option

  • Save rogercbe/71718c028eae977f18f71d0b6e70b01c to your computer and use it in GitHub Desktop.

Select an option

Save rogercbe/71718c028eae977f18f71d0b6e70b01c to your computer and use it in GitHub Desktop.
Abstract code generation to a trait
<?php
namespace App;
use App\Support\Traits\GenerateUniqueCode;
use App\Support\Contracts\GeneratesCodes;
use Illuminate\Database\Eloquent\Model;
class Lead extends Model implements GeneratesCodes
{
use GenerateUniqueCode;
// Override
protected static function getCodeName()
{
return 'lead_code';
}
/**
* Logic to generate a new code.
*
* @return string
*/
protected function generateCode()
{
return strtoupper(substr(md5(str_random(16)), 0, 8));
}
}
<?php
namespace App\Support\Contracts;
interface GeneratesCodes
{
/**
* Logic to generate a code.
*
* @return mixed
*/
function generateCode();
}
<?php
trait GenerateUniqueCode
{
/**
* Boot the trait.
*/
protected static function bootGenerateUniqueCode()
{
static::creating(function ($model) {
$model->attributes[static::getCodeName()] = $model->generateUniqueCode();
});
}
/**
* Determine the name of the code column.
*
* @return string
*/
protected static function getCodeName()
{
return 'code';
}
/**
* Make sure the code is unique for the model.
*
* @return string
*/
protected function generateUniqueCode()
{
$code = $this->generateCode();
while (static::where(static::getCodeName(), $code)->exists()) {
$code = $this->generateCode();
}
return $code;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment