Creating a Blog Using Laravel 4 Part 3: Routing

Creating a Blog Using Laravel 4 Part 3 Routing
Laravel 4 Blog Tutorial – Routing Screenshot

Previous parts of this tutorial:

Topics we have covered so far:

  • Laravel Setup
  • Laravel Migrations
  • Model creation using Eloquent ORM
  • Database Seeding
  • Controllers

Today we will cover the routing for our blog application. So, let’s get started.

Routing in Laravel

Routing plays an essential role in the core workings of any MVC framework. It specifies a mapping between requests and response generators i.e, controller actions. In other words, routing defines the entry points of a web application. A flexible routing provides a greater control over the flow of a web application.
Laravel has a very powerful routing component built right on the top of Symfony’s routing component, and provides you with a very easy to use interface and a rich set of functionalities.

Defining Routes

In Laravel we define our application’s routes in app/routes.php. A simple routes.php would look like this:


// will be used to handle GET requests.
    echo 'this is index page';

    echo 'GET login requests will be hndled here.';

// will be used to handle POST requests.
Route::post('login', function() 
    echo 'POST login requests will be handled here.';

We can also use controller actions instead of closures like:

Route::get('users', 'UsersController@getIndex');

In this case all requests to /users will be delegated to the getIndex() action of the UserController. We can also define routes for delete and put HTTP verbs using Route::put and Route::delete methods.

Route Parameters


// parameter {id} will be passed to the closure.
    echo "post with id: $id";

//binding models to route parameters.
Route::model('post','Post'); //binds a model to the route parameter {post}

// A model with given post id will be passed to closure for any HTTP request.
    echo "post with id: $post->id";

Named Routes and Route Filters

Route filters provide a convenient way of limiting access to a given route, which is useful for creating areas of your site which require authentication. There are several filters included in the Laravel framework, including an auth filter, an auth.basic filter, a guest filter, and a csrf filter. These are located in the app/filters.php file.
Laravel’s Official Documentation

We define and apply a filter to a given route as follows:

Route::filter('simpleBeforeFilter', function()
    echo 'this is simple before filter';

    echo 'simpleBeforefilter is already called';

We can name any route by defining a key as in the array we pass as second argument:


    echo 'simpleBeforefilter is already called';

//another example using controller action.
Route::get('/post/list',['as' => 'post.list','uses' => 'PostController@listPost']);

Naming a route makes it easier to generate URLs and redirects, for example:

URL::route('post.list'); //generates a url to /post/list route.

Laravel’s official documentation explains a lot of features of routing component. Covering each and every aspect of routing here is beyond the scope of the article. Please refer to the documentation page here for further details and clarifications.

Creating Routes for Blog Application

The following routes will define the flow of our blog application:

//file: app/routes.php

/* Model Bindings */

/* User routes */
Route::get('/post/{post}/show',['as' => '','uses' => 'PostController@showPost']);
Route::post('/post/{post}/comment',['as' => '','uses' =>'CommentController@newComment']);

/* Admin routes */
Route::group(['prefix' => 'admin','before'=>'auth'],function()
    /*get routes*/
        $layout = View::make('master');
        $layout->title = 'DashBoard';
        $layout->main = View::make('dash')->with('content','Hi admin, Welcome to Dashboard!');
        return $layout;

    Route::get('/post/list',['as' => 'post.list','uses' => 'PostController@listPost']);
    Route::get('/post/new',['as' => '','uses' => 'PostController@newPost']);
    Route::get('/post/{post}/edit',['as' => 'post.edit','uses' => 'PostController@editPost']);
    Route::get('/post/{post}/delete',['as' => 'post.delete','uses' => 'PostController@deletePost']);
    Route::get('/comment/list',['as' => 'comment.list','uses' => 'CommentController@listComment']);
    Route::get('/comment/{comment}/show',['as' => '','uses' => 'CommentController@showComment']);
    Route::get('/comment/{comment}/delete',['as' => 'comment.delete','uses' => 'CommentController@deleteComment']);

    /*post routes*/
    Route::post('/post/save',['as' => '','uses' => 'PostController@savePost']);
    Route::post('/post/{post}/update',['as' => 'post.update','uses' => 'PostController@updatePost']);
    Route::post('/comment/{comment}/update',['as' => 'comment.update','uses' => 'CommentController@updateComment']);


/* Home routes */

In the above code the initial two statements will bind the Post and Comment models to the route parameters. The next two routes and will be used for displaying a single post and allowing the users of the blog to post the comments respectively.

Next we are defining a group of routes for the administration. A prefix admin is applied to differentiate them from user routes. Using named routes inside admin route group will make it easier to generate complex URLs ( e.g, URL::route('post.edit',12) will generate a URL: http://localhost/admin/post/12/edit ).

Protecting Admin Routes and Authentication

Laravel comes with some predefined filters including an auth and a guest filter. auth filter checks if a current user is logged in otherwise it redirects the user to the login page. The guest filter is the counter part of the auth filter.

Here is the code for the auth filter:


//file: app/filters.php
Route::filter('auth', function()
    if (Auth::guest()) return Redirect::guest('login');

As you can see in the code of the app/routes.php, I have already applied this filter to the admin group of the routes. So, whenever we will try to access one of the routes in the admin route group, this filter will ensure that a user is logged in to the application.

Note on Authentication:
A users table is required in the database for the Auth component to work properly. You can refer to my previous article on Laravel Authentication for database setup and other details.

In the next part of this tutorial we will create the layout and views for the application. Regards!