Skip to content

Instantly share code, notes, and snippets.

@amenk
Last active August 29, 2015 14:23
Show Gist options
  • Save amenk/f1b4edf6f296ca0230c5 to your computer and use it in GitHub Desktop.
Save amenk/f1b4edf6f296ca0230c5 to your computer and use it in GitHub Desktop.
Friendly Detail Page URLs in Laravel 5
class Activity extends Model
{
/**
* Convert a string to ASCII
*
* @source http://cubiq.org/the-perfect-php-clean-url-generator
* @param $str
* @param array $replace
* @param string $delimiter
* @return string
*/
public function toAscii($str, $replace=array(), $delimiter='-') {
if( !empty($replace) ) {
$str = str_replace((array)$replace, ' ', $str);
}
$clean = iconv('UTF-8', 'ASCII//TRANSLIT', $str);
$clean = preg_replace("/[^a-zA-Z0-9\/_|+ -]/", '', $clean);
$clean = strtolower(trim($clean, '-'));
$clean = preg_replace("/[\/_|+ -]+/", $delimiter, $clean);
return $clean;
}
/**
* Check if the alias is a registered route
*
* @param $alias
* @return bool
*/
protected function isBlacklisted($alias)
{
$routes = \Route::getRoutes();
foreach($routes->getRoutes() as $route) {
$parts = explode('/', $route->getUri());
if (count($parts) > 0 && $parts[0] == $alias) {
return true;
}
}
return false;
}
protected function generateAlias() {
$ascii = $this->toAscii($this->name);
$alias = $ascii;
$increment = 0;
while (self::whereAlias($alias)->count() > 0 || $this->isBlacklisted($alias)) {
$increment++;
$alias = $ascii . '-' . $increment;
}
return $alias;
}
public function save(array $options = array())
{
if ($this->alias == '') {
$this->alias = $this->generateAlias();
}
parent::save();
}
// as last entry
Route::get('{alias}', 'WelcomeController@getDetail');
class WelcomeController extends Controller {
public function getDetail($alias){
$activity = Activity::whereAlias($alias)->first();
return view('detail')
->with('activity', $activity);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment