It seems like you are using an ad blocker. To enhance your experience and support our website, please consider:

  1. Signing in to disable ads on our site. Our users don't see ads
  2. Or, Sign up if you don't have an account yet
  3. Or, disable your adblocker by doing this:
    • Click on the adblocker icon in your browser's toolbar.
    • Select "Pause on this site" or a similar option for lancecourse.com.

Laravel for Tortoises - part 4: Routing

By zooboole

Welcome to part 4 of this series on Laravel. In part 3 we learnt how to install the framework. We also went through some problems that could happen during the installation.

In this part we'll be tackling the entry point of the Laravel framework and most applications which is the routing

What is routing and why is it important?

I could simply start dropping some Laravel routes right here to show you how to do it. But Laravel routing is so simple(and sweet) that if a beginner doesn't pay close attention he will pass by its real beauty. So, I've decided to give a deep explanation.

A route is a path or a way to get from one place to another. It's actually the path through which an information flows. So, routing is the principle in which decisions are made on how an information takes or goes through a specific path in a given system.

If you remember in part 2 I made mention of HTTP requests that are crucial in web applications such as Laravel framework. Anytime you type a website(URL) in the address bar, the request goes from your browser(the client) to the server hosting the website. So the server will check the type of request(POST, GET, PUT, or DELETE) you've made, and check also the specific resource(path) you are requesting for(http://site.com for home page and http://site.com/about for the about page). Base on that the server can now send back a response with all the information requested. Then your browser will be in charge of displaying it accordingly like in the following illustration.

Routing Laravel

An HTTP request is considered as an event by the MVC framework. And the router is the component in charge of translating each incoming HTTP request to an action.

Laravel provides a powerful routing system that allows to define both RESTful paths(http//site.com/restful/path) and HTTP verbs to use during a request easily.

Old picture

Formally when you build a website you create a file for each page. if you have an about page you create a file about.php. For a contact page you create a file contact.php, and so on so fourth. To access this pages you just had to type http://your-site.com/about.php.

With that the URLs are not nice and it becomes hard to maintain your source code. But the routing concept is still there though it's hard to do. So we understand the importance of our URLs. They actually define how we structure our code; how different part are linked to each other and how they interact.

With Laravel framework, it's easy to structure your URLs and your URLs are RESTful like: http://laravel.com/docs/5.1/routing. It's meaningful.

How to route with Laravel framework?

To demonstrate that very well let's assume we need a little website that has a home page and an about page. Previously when you launched your application you used http://localhost:8000/ which is the URL on which your Laravel application is served. In order to access our pages we will be entering http://localhost:8000/ for the home page and http://localhost:8000/about for the about page. The first one will give you the default laravel page. But as soon as you enter the second one you will have the following error:

Laravel 404

If it happens that you have only this:

Sorry, the page you are looking for could not be found.

Open the .env file and look for

APP_ENV=local
APP_DEBUG=false

Turn the APP_DEBUG into true. That way it will show you more details on each error that occurs. This is very useful while you are still developing the application. Once you are done and you are ready to host(deploy) your site, you can turn it off(make it false) so that it wouldn't show detailed errors to your users.

So we have an error that says that the page we're looking for could not be found. All we have to do now is just to create that page. Simple, since Laravel is using an MVC model it means we need a View to display our page. In Laravel 5, views are stored in the folder resources/views. If you open this folder you will see the welcome page's view called welcome.blade.php. If you open that file with your text editor you will see the Laravel 5 that shows up when you launch Laravel 5. Feel free to play a bit with the content. Change the Laravel 5 into Home page and we have our home page ready.

Now let's create our missing view in that folder so that Laravel can see it. But before then note the name of the other view inside: welcome.blade.php. Actually you can omit the blade and just name it welcome.php. It's all fine. Laravel gives you the possibility of doing both. Further in this tutorial we will go deep in that aspect.

For now let's create our view and name it about.blade.php beside the welcome.blade.php. Enter the following content in your about page:

<h2>About us</h2>

<p>We're the Laravel lovers.</p>

And go and refresh your browser.

Obviously I deceived you. You are still having the same error. Yes, it's normal because we're still having a little information to provide to make Laravel really find our file. Remember that by entering http://localhost:8000/about you are making an HTTP request. Laravel has to analyze that request and take an appropriate action.

In order to do that we have to create a route that will check what we want. Basically to create a route it's very easy. Most of our routes will be defined in the file app/Http/routes.php. Open that file with your text editor you should see this:

<?php

/*
|--------------------------------------------------    ------------------------
| Application Routes
|--------------------------------------------------    ------------------------
|
| Here is where you can register all of the routes     for an application.
| It's a breeze. Simply tell Laravel the URIs it     should respond to
| and give it the controller to call when that URI     is requested.
|
*/

Route::get('/', function () {
    return view('welcome');
});

Aside the comment you have this code

Route::get('/', function () {
    return view('welcome');
});

This is called a route. This particular route is the one that allows you to display the home page.

So let's add one for our about page:

Route::get('/about', function () {
    return view('about');
});

Now refresh your browser. Bingo! you should have this:

Laravel Lover

So with this principle you can easily set up a company profile in less that an hour. All you have to do is to create a route for each page you have, add a view for it and you are good to launch your new website. Not great !?

Dissection of the route

Before you surprise your boss with your new spider-man tool, let's see how the rout is actually defined.

Basically a route is comprised of one main functions:

Route::get()

That can also be written like get();

This function takes two main parameters: the URI and an anonymous function. All the anonymous function does here is to return a view with return View('nameOfView'); Since the the second parameter is a function it can actually return a string directly using any traditional way(print(), echo(), die(), return, etc); We could have written that about route like:

Route::get('about', function () {

    echo "About us";

});

Route::get('about', function () {

    return "About us";

});

get('about', function () {

    print "About us";

});

Note: the forward slash before the about is not necessary except for the main route.

More routing

You may be wondering how come Laravel gives so much flexibility for the same thing. You are right. It uses something special functions called Helpers. They like interpreters of little little needs the framework has. We will go deep into that later on.

The other aspect with the route is that sometimes you may like to request a resource using some parameters like in the following url: http://phpocean.com/tutorials/id where the id defines a specific tutorial. In such cases you can write your route like this:

get('tutorial/{id}', function ($id) {

    print "Requesting tutorial number : ".$id;

});

If you browse http://localhost:8000/tutorials/2 you should have Requesting tutorial number : 2.

Now what if instead of 2 I type in someString ?

Laravel will simply spit : Requesting tutorial number : someString.

Here Laravel did not understand that it's a string and we're expecting an integer. To prevent such behavior you can add a regex to specify the type of data to accept:

get('tutorial/{id}', function ($id) {

    print "Requesting tutorial number : ".$id;

})->where('id', '[0-9]');

Now if you enter a string Laravel will tell you that the page can not be found.

Another thing you need to notice is the way the variable $id was set just through the string {id}. Then it is passed to the second parameter as the parameter of the closure(anonymous function).

Actually you should be asking yourselves What is going on with HTTP requests. The method used to register our route is actually the HTTP verb: GET. So it's the same way you could register routes with other verbs like following:

Route::post('route/test', function () {
    return 'Testing';
});

Route::put('route/foo', function () {
    return 'put';
});

Route::delete('route/del', function () {
    return 'delete';
});

Conclusion

In this part we just discovered how we could easily route a request in Laravel and how the framework gives use the flexibility in that.

We are very far from discovering the deep aspect of routing in Laravel framework like route with optional parameters, named routes,route groups, sub-domain routing, etc. During this series we'll surely have the opportunity to see them as we get used to the framework. For now we are taking it lightly and easy.

In this part we have seen that we could route a request to a view. We can do more, and more processing before rendering the view with the help of controllers. Remember Laravel uses the MVC pattern! That will be our next talk in this series. See you then.

Last updated 2024-01-17 UTC