Question

I just started learning Laravel but i can't seem to get a thing done. Because i'm a beginner i don't know where to search for. But this is the idea:

  • I have one controller for my CMS pages.
  • I have an existing db with content with the fields Id - Title - Alias
  • The 'Alias' is used to build the URL (like: http://site.tld/about-us) and i use it like this in my routing:

    Route::get('about-us', array('uses' => 'CmsController@showByAlias'));
    Route::get('article-1-title', array('uses' => 'CmsController@showByAlias'));
    

I can get everything to work the easy way, but i need to have things more dynamic. What i want to know is: How do i get the Id from the database using the route title (i.e. 'about-us' or 'article-1-title')?

Was it helpful?

Solution

You need to use the optional parameters routing within Laravel, as described in Laravel documentation.

Add the following to your routes.php. This will handle any other URL except the index page. If you need any other static URLs, add them before this line.

Route::get('/{alias}', array('uses' => 'CmsController@showByAlias'));

Now you need to define the controller that will handle the route. It could be something like this:

class CmsController extends BaseController {

  public function showByAlias($alias)
    {
    $content = Cms::findByAlias($alias);
    return View::make('cms.show')->with('content', $content)->with('title',$title);
    }

You still need to write a function such as Cms::findByAlias in your model to retrieve and process the proper content from database. Of course you can do this within the controller itself.

Also note that you need to add error handling in case an invalid alias is passed within the URL. E.g. show a 404 error page in that case.

Just a hint: I am doing a very similar thing within my Laravel application. I am storing all CMS content in markdown format, and converting that to HTML within Laravel using Parsedown, before passing it to the view. Suits my needs perfectly.

OTHER TIPS

You can use Route model binding.

For example:

// Assume you have posts table and you have a Post model.

Route::bind('post', function($value, $route) {
    return Post::whereTitle($value)->firstOrFail();
});


Route::get('article/{post}', array('uses' => 'CmsController@showByAlias'));

In your controller:

Public function showByAlias(Post $post) 
{
  dd($post->id);
}

Reference:

http://laravel.com/docs/routing#route-model-binding

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top