Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

Building Web Applications with Laravel Framework

Many of you may have already heard about Laravel, but might not just have started to work with it yet. In this tutorial, we shall see what the Laravel framework offers and then learn about how you can build your first web application using it.

Laravel – What exactly is it?

Laravel happens to be a very popular framework that is meant for developing PHP applications. It comes across as a very clean and good framework for developing web applications. Considering that developing applications should be a wonderful experience, Laravel is fairly simple and allows for expressive syntax.

Also, another very good aspect of using Laravel is that it frees you from using spaghetti code. Developers who have used Laravel always state that it brings forward three very important qualities.

  • Simple in nature – several functionalities that Laravel offers is very simple to grasp and understand. If you love simple programming style, you’d surely stick with Laravel.
  • Fairly elegant – Even with very little configuration involved, Laravel’s functions are known to run seamlessly. It also relies on conventions specified in the industry that allows or the prevention of code-bloating.
  • Very well-documented – Laravel always offers updated and complete documentation. The creator even updates the documentation before a new version is released. This makes it pretty easy for people who are just learning the framework.

Making an application from scratch

Now that we just about have an idea about Laravel is, we shall go ahead and build a web application. Here, we shall basically build an Instagram-like application, which will allow us to post photos and also like and comment on them. Besides, you can also follow others.

Downloading Laravel and important files

Before we just about start coding our app, there are some things that need to be taken care of. You shall need –

  • PHP 5.3.X or higher
  • FileInfo library – On Windows computers, you will need to add the extension in the PHP.ini file.
  • Mcrypt library – It usually comes with PHP, and is required by Laravel for encryption and generation of hashes.

After setting up the environment, the next immediate step is to download Laravel, along with all the necessary libraries. We shall require –

Inside the root folder of Laravel, you shall see that there is a public folder, where file meant to be publicly accessed must be stored. Since there are some predefined folders already, such as images, css, js etc, you can place the Twitter Bootstrap and jQuery files in their likely folders.

Setting up of encryption key, URLs and virtual host

Before writing code, a certain encryption key is required for Laravel. We shall need this for the encryption of data that may be required, like cookies. Open the file application/config/application.php and locate the key. Here, we change the default value to blank.

/*
|--------------------------------------------------------------------------
| Application Key
|--------------------------------------------------------------------------
|
| This key is used by the encryption and cookie classes to generate secure
| encrypted strings and hashes. It is extremely important that this key
| remain secret and should not be shared with anyone. Make it about 32
| characters of random gibberish.
|
*/
 
'key' => '',

Now, fire up the Terminal/Command Prompt and then go to Laravel’s root directory. Then generate the key using –

php artisan key:generate

This will automatically generate a 32 character key for encryption in Laravel.

The next step that we take is to accept petty URLs and work without the pointing of requests to index.php. In the same file for the key, look for –

/*
|--------------------------------------------------------------------------
| Application Index
|--------------------------------------------------------------------------
|
| If you are including the "index.php" in your URLs, you can ignore this.
| However, if you are using mod_rewrite to get cleaner URLs, just set
| this option to an empty string and we'll take care of the rest.
|
*/
 
'index' => 'index.php',

Then, set the index to a blank string.

The last requirement is to set up a virtual host for Laravel. This is important foe we do not wish to allow access to the Laravel library and application files. As such, all publicly accessible fiels need to go to the public folder, which is also where our domain should point to.

While the configuration of a virtual host depends on the browser in use, the Apache Web Server can use –

<VirtualHost *:80>
    ServerName instantpiks.com
    DocumentRoot "D:/Development/instantpiks/public"
    <Directory "D:/Development/instantpiks/public">  
    </Directory>
</VirtualHost>

Also, we will need to add the domain (instantpiks.com) to our host files because the domain actually does not exist. For Windows systems, simply edit C:\Windows\System32\drivers\etc\hosts, and for Linux, edit /etc/hosts. Add the line given to the file - 127.0.0.1 instantpiks.com

This step informs the machine that the domain name instantpiks.com resolves to the address 127.0.0.1, which is but the local computer.

Setting up routing

All requests to the application in Laravel are mapped to methods and controllers using Routes. These point out to the application where URLs need to go. Say, to go to http://instantpiks.com/ home, which renders the home file, we can create a route within the routes.php file.

Route::any('home', function()
{
    return View::make('home.index');
})

Now, say we wish to route http://instantpiks.com/home to a Controller, such as the home.php controller. This is what we can do –

Route::controller('home');

This step would route to the file controller, home.php.

A very important point to take note of here would be that Laravel does not route controller by default, unlike many other PHP frameworks. However, by doing so, it allows us to create simple pages without a controller for them. As such, a Contact Us page that just provides contact information can be made like –

Route::any('contactUS', function()
{
    return View::make('home.contactUS’);
})
 

This routes http://instantpiks.com/contactUS and displays the application/views/home/contactUS.php file.

Considering that the page does not have any dynamic processing involved, we can simple render the file for view and not have to spend time setting up a controller for it.

Creation of the first Laravel Controller

The application/controllers folder is home to Controllers in Laravel. The Home Controller accepts requests sent to the root of the Laravel application by default. Like, if you are going to http://instantpiks.com, it will go to the Home--> actionindex() method.

Now, in order to create a controller, the first step is to go to applications/controllers and then create a file there. The file name is usually set to something descriptive, which will also be the name of the controller class. Here, we shall create the controller Login, for login purpose.

class Login_Controller extends Base_Controller
{    
    public function actionindex()
    {
        //we shall carry out the login mechanism 
        echo 'Testing'; //echo test is to test this controller 
    }
}

Now, if you happen to open your browser and http://instantpiks.com/login, you shall see the “Testing” message that we had placed in the controller. Also, since we have already set to enable routes to the controller in the routes.php file, this will work without the need for any additional work.

Base Controller

Many of the controllers in Laravel tend to extend the Base_Controller. This allows for a way to define functions, which will be the same for all controllers. Here, we will create a method for logging, which will log all controller requests.

Listing 1: Method for logging

class Base_Controller extends Controller {
 
    /**
     * Catch any method for those requests that cannot be matched.
     *
     * @param  string    $methd
     * @param  array     $parameter
     * @return Response
     */
    public function __call($methd, $parameter)
    {
        return Response::error('404');
    }
     
    public function logrequst()
    {
        $Route = Request::Route();
        Log::log('request', "Controller: {$Route->controller} / Action: {$Route->controller_action} called at ". date('d-m-Y H:i:s'));
    }
}

Now, whenever we wish to log any request, we can just call $this-->logrequst(); from any controller.

We shall look to update the Home controller now. For that, we shall require to add a method actionabout, for we created http://instantpiks.com/about route for directing to this method. You can open application/controllers/home.php and update.

Listing 2: Updating the Home controller

class Home_Controller extends Base_Controller {
 
    public function actionindex()
    {
        return View::make('home.index');
    }
 
    public function action_about()
    {
        return View::make('home.about');
    }
}

Creation of first Laravel View with Blade Template Engine

There are two ways to generate view for an application developed in Laravel. One is the PHP-based Views, which use PHP as the language for templates. Another is the Blade-based Views. These make use of Laravel’s built-in template engine.

The Blade Templating Engine makes use of customized tags and methods that permit a better separation of application code and the presentation logic. Also, for simplicity, we shall make use of Blade Templating Engine. All of the view files are required to make use of the .blade.php extension, which tells Laravel to use that particular engine for a view file.

Now, we will first create a general purpose layout meant for all the views. Go to application/views/layouts folder and then create main.blade.php file.

Listing 3: General purpose layout

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>Instantpiks</title>
        {{ Asset::styles() }}
        {{ Asset::scripts() }}
    </head>
 
    <body>
        <div class="navbar navbar-fixed-top">
            <div class="navbar-inner">
                <div class="container">
                    <a class="brand" href="home">Instantpiks</a>
                    <div class="nav-collapse">
                        <ul class="nav">
                            @section('navigation')
                            <li class="active"><a href="home">Home!</a></li>
                            @yield_section
                        </ul>
                    </div><!--/.nav-collapse -->
                </div>
            </div>
        </div>
 
        <div class="container">
            @yield('content')
            <hr>
            <footer>
            <p>© Instantpiks 2016</p>
            </footer>
        </div> <!-- /container -->
    </body>
</html>

After this, we shall look to update the index file. Open the file application/views/home/index.blade.php and update.

Listing 4: Updating index file

@layout('layouts/main')
@section('navigation')
@parent
<li><a href="/about">About!</a></li>
@endsection
@section('content')
<div class="hero-unit">
    <div class="row">
        <div class="span6">
            <h1>Welcome to Instantpiks!!!</h1>
            <p>Instantpiks is a great way to share photos with friends and people.</p>
            <p>You can surprise them with your photo-filtering know-hows!</p>
            <p>Allow them to sense the great photographer in you!</p>
            <p><a href="about" class="btn btn-primary btn-large">Learn a lot more »</a></p>
        </div>
         <div class="span4">
            <img src="http://net.s5.amazonws.com/2065_laravel/imgs/phon.png" alt="Instantpiks!" />
        </div>
    </div>
 </div>
 <!-- Example row of columns -->
<div class="row">
    <div class="span3">
         
    </div>
    <div class="span4">
        <a href="#"><img src="http://net.s5.amazonws.com/2065_laravel/img/badgios.png" alt=" iOS" /></a>
    </div>
    <div class="span4">
        <a href="#"><img src="http://net.s5.amazonws.com/2066_laravel/img/badgedroid.png" alt=" You can get it for Android" /></a>
    </div>
</div>
@endsection

Now, we shall finally look to pass some variable to the views and check them out. The first step would be to create a new file about.blade.php in the folder application/views/home.

Listing 5: Passing variable to views

@layout('layouts/main')
 
@section('navigation')
@parent
<li><a href="about">About!</a></li>
@endsection
 
@section('content')
<div class="row">
    <div class="span3">
        <div class="well sidebar-nav">
            <ul class="nav nav-list">
                <li class="nav-header">Navigation!</li>
                @foreach ($sidenavi as $sn)
                <li @if ($sni['active']) class="active" @endif>
                    <a href="{{ $sni['url'] }}">{{ $sni['name'] }}</a>
                </li>
                @endforeach
            </ul>
        </div>
    </div>
    <div class="span9">
        <h1>About Instantpiks..</h1>
        <p>You can fill in all the details about Instantpiks in this space      provided to you.</p>
    </div>
</div>
@endsection

So, we come back to the Home controller and then update the method actionabout().

Listing 6: Updating the action about method

public function actionabout()
{
    return View::make('home.about', array(
        'sidenavi' => array(
            array(
                'url' => 'home',
                'name' => 'Home',
                'active' => false
            ),
            array(
                'url' => 'about',
                'name' => 'About',
                'active' => true
            )
        )
    ));

If you see the Home controller, you might have noticed that we have set hardcoded values. However, this can actually come from anywhere; say a database or a model.

Now let’s check a dashboard with photo views.

Following is the controller class.

class DBoard_Controller extends Base_Controller
{
    public function action_index()
    {
        $photos = Auth::user()->photos()->order_by('created_at', 'desc')->order_by('id', 'desc')->get();
        return View::make('dashboard.index', array('photos' => $photos));
    }
}

Next is the changed controller class to show the images.

 
public function action_insert_photo_data()
{
    $logged_in_user = Auth::user();
     
    for( $x = 0; $x < 10; $x++ ) {
        $email = rand().'@yahii.com';
        $user = new User();
        $user->email = $email;
        $user->password = Hash::make($email);
        $user->save();
         
        $logged_in_user->followers()->attach($user->id);
        if( $x > 5 ) {
            $logged_in_user->following()->attach($user->id);
        }
    }
     
    $photos = array(
        array(
            'user_id' => $logged_in_user->id,
            'location' => 'http://farm6.staticflickr.com/5044/5319042359_68fb1f91b4.jpg',
            'description' => 'Dusty Memories, The Girl in the Black Beret (http://www.flickr.com/photos/cloudy-day/)'
        ),
        array(
            'user_id' => $logged_in_user->id,
            'location' => 'http://farm3.staticflickr.com/2354/2180198946_a7889e3d5c.jpg',
            'description' => 'Rascals, Tannenberg (http://www.flickr.com/photos/tannenberg/)'
        ),
        array(
            'user_id' => $logged_in_user->id,
            'location' => 'http://farm7.staticflickr.com/6139/5922361568_85628771cd.jpg',
            'description' => 'Sunset, Funset, Nikko Bautista (http://www.flickr.com/photos/nikkobautista/)'
        )
    );
    $logged_in_user->photos()->save($photos);
}

Now refresh the page and the following output will be displayed.

Building Web Applications with Laravel Framework

Figure 1: Output

Conclusion

In this tutorial, we have covered Laravel as it should be done for a beginner to the framework. We started with what Laravel basically is, moved to how you can set it up, and then learnt about its routing systems and controllers. Finally, we ended with the views, using Laravel’s Blade Templating Engine.



Website: www.techalpine.com Have 16 years of experience as a technical architect and software consultant in enterprise application and product development. Have interest in new technology and innovation area along with technical...

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login