Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save mkwsra/f7e8252710a17cf032b59e7492ff8176 to your computer and use it in GitHub Desktop.
Save mkwsra/f7e8252710a17cf032b59e7492ff8176 to your computer and use it in GitHub Desktop.
<?php
namespace App\Traits;
use App\Http\Controllers\Controller;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
trait HasUuid
{
protected static function boot()
{
parent::boot();
static::creating(function ($query) {
$query->uuid = Controller::uuid();
});
}
/**
* Get the route key for the model.
*
* @return string
*/
public function getRouteKeyName()
{
return 'uuid';
}
/**
* @param Model $model
* @param Request $request
* @param string $idSource
* @param string $slugSource
*
* @return bool
*/
public static function adjustShowURLSlug(
Model $model,
Request $request,
string $slugSource = 'title',
string $idSource = 'uuid'
): bool {
$urlExploded = explode('/', urldecode($request->getRequestUri()));
$slugAndUuid = $urlExploded[count($urlExploded) - 1];
$slug = strstr($slugAndUuid, '-'.$model->{$idSource}, 1);
return $slug !== self::slugify($model->{$slugSource});
}
static function slugify($text)
{
$text = trim(strtolower($text), '-');
return trim(preg_replace('#(\p{P}|\p{C}|\p{S}|\p{Z})+#u', '-', $text), '-');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment