Last active
August 29, 2015 14:23
-
-
Save amenk/f1b4edf6f296ca0230c5 to your computer and use it in GitHub Desktop.
Friendly Detail Page URLs in Laravel 5
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
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(); | |
} |
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
// as last entry | |
Route::get('{alias}', 'WelcomeController@getDetail'); |
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
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