Routing in Laravel

20. April 2016 Beginner, Laravel 2
Routing in Laravel

Here we ‘ll see about routing in laravel. All laravel routes are defined in routes.php file (located at app/Http/routes.php).
Routing is very simple, clear and one of the coolest feature in laravel, we can see all the pages, where they are linked in a single place.

Working Demo      Project on Github

We will see 4 different types of routing,

  • Route returning a view
  • Route returning some static text
  • Routing to a controller which returns a view
  • Routing to  a controller which returns data from database and renders in a view

 

Route returning a view:

When we open routes.php file, we can see a default route which returns a view, it looks like the snippet below,

when we open the browser, and type localhost:8000/, it returns the default view named ‘welcome’

justLaravel - Routing in Laravel
justLaravel – Routing in Laravel

 

Route returning some static text:

We ‘ll define another simple route to display some sample text, when that particular route is called,

When we open the browser, and type localhost:8000/hello, it will return the text ‘Hello World!’ we just gave,

justLaravel - Routing in Laravel
justLaravel – Routing in Laravel

 

Routing to a controller which returns a view:

We ‘ll define one more route, this time it calls the controller, and that controller simply returns a view,

The controller logic for index function would be,

 

When we open the browser, and type localhost:8000/callController, it return the default view named ‘Welcome’

justLaravel - Routing in Laravel
justLaravel – Routing in Laravel

 

 

Routing to a controller which returns data from database and renders in a view:

We ‘ll define another route, it calls the controller, and this controller interacts with model and collects some data from the database, now we ‘ll render that obtained data in the view,

The controller logic for getFromDb function would be,

the view file, sample.blade.php would be,

When we open the browser and type, localhost:8000/callControllerDb, it calls to index controller, which gets data from the database and renders it in the view,

justLaravel - Routing in Laravel
justLaravel – Routing in Laravel

Working Demo      Project on Github

NOTE : This post covers about routing only, other details about models, views and controllers is not covered here



2 thoughts on “Routing in Laravel”

  • 1
    Michelle Prather on December 14, 2016 Reply

    Thank you for such an easy implementation of the search function! My function displays results fine, however, when the search returns no results, the redirect to a different page works, but the message does not show. Any suggestions?

    • 2
      avinash on December 14, 2016 Reply

      Did you redirect it with a message.

Leave a Reply