Dynamic urls in laravel?
For Laravel 4 do this
Route::get('{slug}', function($slug) { $page = Page::where('slug', '=', $slug)->first(); if ( is_null($page) ) // use either one of the two lines below. I prefer the second now // return Event::first('404'); App::abort(404); return View::make('pages.show', array('page' => $page));});// for controllers and viewsRoute::get('{page}', array('as' => 'pages.show', 'uses' => 'PageController@show'));
You could use the route wildcards for the job, you can start with an (:any)
and if you need multiple url segments add an optional (:all?)
, then identify the page from the slug.
For example:
Route::get('(:any)', function($slug) { $page = Page::where_slug($slug)->first(); if ( is_null($page) ) return Event::first('404'); return View::make('page')->with($page);});
Very similar to Charles' answer, but in the controller:
public function showBySlug($slug) { $post = Post::where('slug','=',$slug)->first(); // would use app/posts/show.blade.php return View::make('posts.show')->with(array( 'post' => $post, ));}
Then you can route it like this:
Route::get('post/{slug}', 'PostsController@showBySlug') ->where('slug', '[\-_A-Za-z]+');`
...which has the added bonus of allowing you an easy way to link straight to the slug routes on an index page, for example:
@foreach ($posts as $post) <h2>{{ HTML::link( action('PostsController@showBySlug', array($post->slug)), $post->title )}}</h2>@endforeach