Welcome to the second blog post under Laravel learning notes. In first post, we installed the laravel. If you missed that post, click here to go to day 1.

I am Kapil Sharma, Technical Architect at Eastern Enterprise and working on web technologies since last 10 years. You can find more about me on my personal website kapilsharma.info or contact me through twitter @kapilsharmainfo or contact us from on website.

I am publishing my notes I made for personal reference while learning laravel. Although I do not include very basics of language in my personal notes but since I’m publishing these notes, I’ll add some more basics here for those trying to learn laravel using my notes.

Day 2

Today, we are going to discuss basics of:

  1. Routes

  2. Views

  3. Blade

Views are the part of MVC architecture so if you are not familiar with MVC architecture, please look it on google. MVC basics are out of scope for these notes.

Laravel folder structure

We have already installed Laravel during day 1. Most important folder there is ‘app’ and most of the time, we will be working in that folder. If we open app folder, it contains 10 folders (commands, config, controllers, database, lang, models, start, storage, tests and views) and two files; filters.php and routes.php. Folder Models, Views and controllers, as name suggest separate the code in MVC architecture. Other folder should also be clear by name like config folder contain configuration of our project, tests contains unit test cases, storage store the things like logs, cache etc. Don’t worry a lot about these folders for now, we will go through them one by one in coming days.

For today, we mainly need to focus on views folder, routes.php file and first introduction of blade template.

Config changes

Before we start working on new laravel setup, it is recommended to make two changes in ‘app/config/app.php’ file. Open app.php file and change following two settings

'debug' => true,
'url' => 'http://laravel-learning:8000',

Please change url with your local website url. Again, in following notes, change laravel-learning:8000 to whatever url you have.

Routes

If you worked with core PHP projects, you must know URL basically point to folder structure in our server’s host directory (public or www or whatever configured). However with Apache rewrite module, we can generate search friendly URL. In this way, we point all URL to a single file, known as front controller, and that file identify the URI and load related resources. This is a good way to achieve search engine friendly URL as well as help to manage our resources in better way.

Laravel also have a front controller and it load the resources based on defined routes. These routes are defined in app/routes.php file. If you open routes.php file, it have the following code:

<?php
Route::get('/', function()
{
    return View::make('hello');
});

Laravel has already defined one simple route to load first page that we saw during day 1. In get method or Route class, we are passing first argument as URI that needs to be matched. Single slash ‘/’ defines the root of website like ‘www.example.com’. Second argument is basically a closure which define what action needs to be taken when this route matches. This closure must return the HTML output. In the default example, we are asking to return output of ‘hello’ view. Since all laravel views are present in ‘app/views’ folder, we need not to give name of folder. Also we need not to give the extension of the file. Above closure will actually return HTML from file ‘app/views/hello.php’

Now lets add another route to understand routes in better way. Add following code at the end of route.php file

Route::get('/hello', function()
{
    return 'Hello World';
});

In this, we are registering new route ‘hello’ so URL http://laravel-learning:8000/hello will be handled by this route. Go ahead and try the URL. It will simply print ‘Hello World’. As mentioned above, second argument of ‘get’ function, closure, must return HTML output. In our example, we are returning a simple string so it will be sended back to the browser.

HTTP verbs:

Please note, we used the ‘get’ method of Route class. It represent that request must come as HTTP GET request. If we want to handle post request, we can use ‘post’ method of Route class. If we need to serve a URL for both GET and POST, we can use following code.

Route::match(array('GET', 'POST'), '/hello', function(){});

Route parameters

We can pass query string in the URL to pass some dynamic data. If we expect some data from the URL, we can define that in routes as follow:

Route::get('/hello1/{name}', function($name)
{
    return 'Hello ' . $name;

});

Now if we try URL http://laravel-learning:8000/hello1/Sharma, Output will be ‘Hello Sharma’.

Sometimes, we might want to keep the parameters optional. With routes, we can do that as well.

Route::get('/hello2/{name?}', function($name = 'Kapil')
{
   return 'Hello ' . $name;
});

In this example, please note the ‘?’ in the URL parameter. Also now since parameter is optional, we must provide default value in closure. Now the URL http://laravel-learning:8000/hello2/sharma will print ‘Hello Sharma’ but URL http://laravel-learning:8000/hello2 will print ‘Hello Kapil’.

There are lot more things possible with routes. Please refer http://laravel.com/docs/routing for datailed documentation on routes. Here, we only covered route basics, that we will need today.

Views

Although the closures in routes can return required output to be sent to the client, it is not the right place to do so. Simply because we saw sample output in routes but in real web application, output is not a single string but whole HTML with CSS and Javascript. It must be placed in its own separate file.

In MVC architecture, views are responsible to generate the output using data provided by models.Lets return to the default route code we saw:

Route::get('/', function()
{
   return View::make('hello');
});

As we already discussed, this will load ‘app/views/hello.php’ file. So lets open hello.php file and add following code in that.

<!doctype html>
<html lang="en">
  <head>
    <title>Laravel-learning day 2 by Kapil Sharma</title>
  </head>
  <body>
    <h1>Hello world</h1>
  </body>
</html>

Now lets visit http://laravel-learning:8000 in the browser and we can see the output of above view.

Views are supposed to display dynamic data, right. So in place of world, lets add some name. Change the <h1> line (line 7) above code as follow:

<h1>Hello <?= $name ?></h1>

Obviously we now need to pass variable $name to the view. Let’s update our route to quickly pass the variable.

Route::get('/', function()
{
    $name = 'Kapil';

    return View::make('hello')->with('name', $name);
});

Here we first created variable $name and passed it to view using ‘with’ method of ‘View’ class. Now load the page again and output will greet me (Kapil) in place of world.

If we want to pass multiple variables to view, we can make an array and pass as second parameter of ‘make’ method as follow:

Route::get('/', function()
{
    $input = array('name' => 'Kapil', 'greet' => 'Hi');

    return View::make('hello', $input);
});

And again change line 7 of app/view/hello.php to:

<h1><?= $greet ?> <?= $name ?></h1>

In above example, we passed two variables to view and use them. Similarly, we can pass an many variables as we need to the views.

Blade

Blade is Laravel’s default template engine. As per definition, template engine allow us to insert dynamic data to HTML and help us generating dynamic pages. By this definition, PHP itself is a template engine. PHP started its life as a template language but it did not evolve like one in the recent years. It doesn’t support many features modern template engines should have nowadays and hence many other template engines were created for PHP. Some of most popular PHP template engines are smarty, twig and blade. Arguably twig is more powerful and have more features, blade is faster and easier. Selecting one over other is purely a matter of personal preference.

Only reason to choose blade for these notes (my personal laravel learning) is, blade is created by Taylor (creator of Laravel) thus blade have more support in laravel documentation/community. At later stage, I might try laravel with twig but for now, concentrating on blade.

First lets write our previous view app/views/hello.php with blade syntax.

<!doctype html>
<html lang="en">
  <head>
    <title>Laravel-learning day 2 by Kapil Sharma</title>
  </head>
  <body>
    <h1>{{ $greet }} {{ $name }}</h1>
  </body>
</html>

 

We simply replaced PHP tags with double curly braces. This is how we display variables in blade. A blade template template file have extension ‘.blade.php’ so we also must rename out file to ‘hello.blade.php’. That all, reload the page and we have same page but by using blade template.

There is lot more things that can be done in blade like loops and decisions but we are skipping them for now for more advanced thing.

Next day:

Next in the series is controllers and models and we will be making simple authentication. I’ll update link here soon as I post the blog.