Last active
July 1, 2020 05:28
-
-
Save mkwsra/f7e8252710a17cf032b59e7492ff8176 to your computer and use it in GitHub Desktop.
This file contains 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\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