Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Laravel Application Development Cookbook
Laravel Application Development Cookbook

Laravel Application Development Cookbook: Since Laravel is so versatile, one of the best learning routes is a cookbook. We've included lots of recipes and guidance on building web application, both simple and complex. It's a pick & mix approach that works brilliantly.

By Terry Matula
$28.99 $19.99
Book Oct 2013 272 pages 1st Edition
eBook
$28.99 $19.99
Print
$48.99
Subscription
$15.99 Monthly
eBook
$28.99 $19.99
Print
$48.99
Subscription
$15.99 Monthly

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Buy Now

Product Details


Publication date : Oct 25, 2013
Length 272 pages
Edition : 1st Edition
Language : English
ISBN-13 : 9781782162827
Category :
Languages :
Table of content icon View table of contents Preview book icon Preview Book

Laravel Application Development Cookbook

Chapter 1. Setting Up and Installing Laravel

In this chapter, we will cover:

  • Installing Laravel as a git submodule

  • Setting up a virtual host and development environment in Apache

  • Creating "clean" URLs

  • Configuring Laravel

  • Using Laravel with Sublime Text 2

  • Setting up your IDE to autocomplete Laravel's namespaces

  • Using Autoloader to map a class name to its file

  • Creating advanced Autoloaders with namespaces and directories

Introduction


In this chapter, we'll learn how to get Laravel up-and-running with ease and make sure it's simple to update when any core changes are made. We'll also get our development and coding environment set up to be very efficient so we can focus on writing great code and not have to worry about issues not related to our applications. Finally, we'll look at some ways to get Laravel to automatically do some work for us so we'll be able to extend our application in very little time.

Installing Laravel as a git submodule


There may be a time when we want to have our Laravel installation separate from the rest of our public files. In this case, installing Laravel as a git submodule would be a solution. This will allow us to update our Laravel files through git without touching our application code.

Getting ready

To get started, we should have our development server running as well as have git installed. In the server's web directory, create a myapp directory to hold our files. Installation will all be done in the command line.

How to do it...

To complete this recipe, follow these steps:

  1. In your terminal or command line, navigate to the root of myapp. The first step is to initialize git and download our project files:

    $ git init
    $ git clone git@github.com:laravel/laravel.git
    
  2. Since all we need is the public directory, move to /laravel and delete everything else:

    $ cd laravel
    $ rm –r app bootstrap vendor
    
  3. Then, move back to the root directory, create a framework directory, and add Laravel as a submodule:

    $ cd ..
    $ mkdir framework
    $ cd framework
    $ git init
    $ git submodule add https://github.com/laravel/laravel.git
    
  4. Now we need to run Composer to install the framework:

    php composer.phar install
    

    Tip

    More information about installing Composer can be found at http://getcomposer.org/doc/00-intro.md. The rest of the book will assume we're using composer.phar, but we could also add it globally and simply call it by typing composer.

  5. Now, open /laravel/public/index.php and find the following lines:

    require __DIR__.'/../bootstrap/autoload.php';
    $app = require_once __DIR__.'/../bootstrap/start.php';
    
  6. Change the preceding lines to:

    require __DIR__.'/../../framework/laravel/bootstrap/autoload.php';
    $app = require_once __DIR__.'/../../framework/laravel/bootstrap/start.php';
    

How it works...

For many, simply running git clone would be enough to get their project going. However, since we want to have our framework act as a submodule, we need to separate those files from our project.

First, we download the files from GitHub, and since we don't need any of the framework files, we can delete everything but our public folder. Then, we create our submodule in the framework directory and download everything there. When that's complete, we run composer install to get all our vendor packages installed.

To get the framework connected to our application, we modify /laravel/public/index.php and change the require paths to our framework directory. That will let our application know exactly where the framework files are located.

There's more...

One alternative solution is to move the public directory to our server's root. Then, while updating our index.php file, we'll use __DIR__ . '/../framework/laravel/bootstrap' to include everything correctly.

Setting up a virtual host and development environment in Apache


When developing our Laravel app, we'll need a web server to run everything. In PHP 5.4 and up, we can use the built-in web server, but if we need some more functionality, we'll need a full web stack. In this recipe, we'll be using an Apache server on Windows, but any OS with Apache will be similar.

Getting ready

This recipe requires a recent version of WAMP server, available at http://wampserver.com, though the basic principle applies to any Apache configuration on Windows.

How to do it...

To complete this recipe, follow these steps:

  1. Open the WAMP Apache httpd.conf file. It is often located in C:/wamp/bin/apache/Apach2.#.#/conf.

  2. Locate the line #Include conf/extra/httpd-vhosts.conf and remove the first #.

  3. Move to the extra directory, open the httpd-vhosts.conf file, and add the following code:

    <VirtualHost *:80>
        ServerAdmin {your@email.com}
        DocumentRoot "C:/path/to/myapp/public"
        ServerName myapp.dev
        <Directory "C:/path/to/myapp/public">
            Options Indexes FollowSymLinks
            AllowOverride all
            # onlineoffline tag - don't remove
            Order Deny,Allow
            Deny from all
            Allow from 127.0.0.1
        </Directory>
    </VirtualHost>
  4. Restart the Apache service.

  5. Open the Windows hosts file, often in C:/Windows/System32/drivers/etc, and open the file hosts in a text editor.

  6. At the bottom of the file, add the line 127.0.0.1 myapp.dev.

How it works...

First, in the Apache config file httpd.conf, we uncomment the line to allow the file to include the vhosts configuration files. You can include the code directly in the httpd.conf file, but this method keeps things more organized.

In the httpd-vhosts.conf file, we add our VirtualHost code. DocumentRoot tells the server where the files are located and ServerName is the base URL that the server will look for. Since we only want to use this for our local development, we make sure to only allow access to the localhost with the IP 127.0.0.1.

In the hosts file, we need to tell Windows which IP to use for the myapp.dev URL. After restarting Apache and our browser, we should be able to go to http://myapp.dev and view our application.

There's more...

While this recipe is specific to Windows and WAMP, the same idea can be applied to most Apache installations. The only difference will be the location of the httpd.conf file (in Linux Ubuntu, it's in /etc/apache2) and the path to the public directory for DocumentRoot (in Ubuntu, it might be something like /var/www/myapp/public). The hosts file for Linux and Mac OS X will be located in /etc/hosts.

Creating "clean" URLs


When installing Laravel, the default URL we will use is http://{your-server}/public. If we decide to remove /public, we can use Apache's mod_rewrite to change the URL.

Getting ready

For this recipe, we just need a fresh installation of Laravel and everything running on a properly configured Apache server.

How to do it...

To complete this recipe, follow these steps:

  1. In our app's root directory, add a .htaccess file and use this code:

    <IfModule mod_rewrite.c>
        RewriteEngine On
        RewriteRule ^(.*)$ public/$1 [L]
    </IfModule>
  2. Go to http://{your-server} and view your application.

How it works...

This simple bit of code will take anything we add in the URL and direct it to the public directory. That way, we don't need to manually type in /public.

There's more...

If we decide to move this application to a production environment, this is not the best way to accomplish the task. In that case, we would just move our files outside the web root and make /public our root directory.

Configuring Laravel


After installing Laravel, it's pretty much ready to go without much need for configuration. However, there are a few settings we want to make sure to update.

Getting ready

For this recipe, we need a regular installation of Laravel.

How to do it...

To complete this recipe, follow these steps:

  1. Open /app/config/app.php and update these lines:

    'url' => 'http://localhost/,
    'locale' => 'en',
    'key' => 'Seriously-ChooseANewKey',
  2. Open app/config/database.php and choose your preferred database:

    'default' => 'mysql',
    'connections' => array(
        'mysql' => array(
            'driver'    => 'mysql',
            'host'      => 'localhost',
            'database'  => 'database',
            'username'  => 'root',
            'password'  => '',
            'charset'   => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix'    => '',
            ),
        ),
  3. In the command line, go to the root of the app and make sure the storage folder is writable:

    chmod –R 777 app/storage
    

How it works...

Most of the configuration will happen in the /app/config/app.php file. While setting the URL isn't required, and Laravel does a great job figuring it out without setting it, it's always good to remove any work from the framework that we can. Next, we set our location. If we choose to provide localization in our app, this setting will be our default. Then, we set our application key, since it's best to not keep the default.

Next, we set which database driver we'll be using. Laravel comes with four drivers out of the box: mysql, sqlite, sqlsrv (MS SQL Server), and pgsql (Postgres).

Finally, our app/storage directory will be used for keeping any temporary data, such as sessions or cache, if we choose. To allow this, we need to make sure the app can write to the directory.

There's more...

For an easy way to create a secure application key, remove the default key and leave it empty. Then, in your command line, navigate to your application root directory and type:

php artisan key:generate

That will create a unique and secure key and automatically save it in your configuration file.

Using Laravel with Sublime Text 2


One of the most popular text editors used for coding is Sublime Text. Sublime has many features that make coding fun, and with plugins, we can add in Laravel-specific features to help with our app.

Getting ready

Sublime Text 2 is a popular code editor that is very extensible and makes writing code effortless. An evaluation version can be downloaded from http://www.sublimetext.com/2.

We also need to have the Package Control package installed and enabled in Sublime, and that can be found at http://wbond.net/sublime_packages/package_control/installation.

How to do it...

For this recipe, follow these steps:

  1. In your menu bar, go to Preferences then Package Control:

  2. Choose Install Package:

  3. Search for laravel to see the listing. Choose Laravel 4 Snippets and let it install. After it's complete, choose Laravel-Blade and install it.

How it works...

The Laravel snippets in Sublime Text 2 greatly simplify writing common code, and it includes pretty much everything we'll need for application development. For example, when creating a route, simply start typing Route and a list will pop up allowing us to choose which route we want, which then automatically completes the rest of the code we need.

There's more...

Installing the Laravel-Blade package is helpful if we use the Blade template system that comes with Laravel. It recognizes Blade code in the files and will automatically highlight the syntax.

Setting up your IDE to autocomplete Laravel's namespaces


Most IDEs (Integrated Development Environment) have some form of code completion as part of the program. To get Laravel's namespaces to autocomplete, we may need to help it recognize what the namespaces are.

Getting ready

For this recipe, we'll be adding namespaces to the NetBeans IDE, but the process will be similar with others.

How to do it...

Follow these steps to complete this recipe:

  1. Download the following pre-made file that lists the Laravel namespaces: https://gist.github.com/barryvdh/5227822.

  2. Create a folder anywhere on your computer to hold this file. For our purposes, we'll add the file to C:/ide_helper/ide_helper.php:

  3. After creating a project with the Laravel framework, navigate to File | Project Properties | PHP Include Path:

  4. Click on Add Folder… and then add the folder at C:/ide_helper.

  5. Now when we start typing the code, the IDE will automatically suggest code to complete:

How it works...

Some IDEs need help understanding the syntax of a framework. To get NetBeans to understand, we download a list of all the Laravel classes and options. Then, when we add it to the Include Path, NetBeans will automatically check the file and show us the autocomplete options.

There's more...

We can have the documents downloaded and updated automatically using Composer. For installation instructions, visit https://github.com/barryvdh/laravel-ide-helper.

Using Autoloader to map a class name to its file


Using Laravel's ClassLoader, we can easily include any of our custom class libraries in our code and have them readily available.

Getting ready

For this recipe, we need to set up a standard Laravel installation.

How to do it...

To complete this recipe, follow these steps:

  1. In the Laravel /app directory, create a new directory named custom, which will hold our custom classes.

  2. In the custom directory, create a file named MyShapes.php and add this simple code:

    <?php
    class MyShapes {
        public function octagon() 
        {
            return 'I am an octagon';
        }
    }
  3. In the /app/start directory, open global.php and update ClassLoader so it looks like this:

    ClassLoader::addDirectories(array(
    
        app_path().'/commands',
        app_path().'/controllers',
        app_path().'/models',
        app_path().'/database/seeds',
        app_path().'/custom',
    
    ));
  4. Now we can use that class in any part of our application. For example, if we create a route:

    Route::get('shape', function()
    {
        $shape = new MyShapes;
        return $shape->octagon();
    });

How it works...

Most of the time, we will use Composer to add packages and libraries to our app. However, there may be libraries that aren't available through Composer or custom libraries that we want to keep separate. To accomplish this, we need to dedicate a spot to hold our class libraries; in this case, we create a directory named custom and put it in our app directory.

Then we add our class files, making sure the class names and filenames are the same. This could either be classes we create ourselves or maybe even a legacy class that we need to use.

Finally, we add the directory to Laravel's ClassLoader. When that's complete, we'll be able to use those classes anywhere in our application.

See also

  • The Creating advanced Autoloaders with namespaces and directories recipe

Creating advanced Autoloaders with namespaces and directories


If we want to be sure that our custom classes don't conflict with any other class in our app, we will need to add them to a namespace. Using the PSR-0 standard and Composer, we can easily autoload these classes into Laravel.

Getting ready

For this recipe, we need to set up a standard Laravel installation.

How to do it...

To complete this recipe, follow these steps:

  1. Inside the /app directory, create a new directory named custom, and inside of custom, create a directory named Custom, and in Custom, create a directory named Shapes.

  2. Inside the /app/custom/Custom/Shapes directory, create a file named MyShapes.php and add this code:

    <?php namespace Custom\Shapes;
    
    class MyShapes {
        public function triangle() 
        {
            return 'I am a triangle';
        }
    }
  3. In the root of the application, open the composer.json file and locate the autoload section. Update it so it looks like this:

    "autoload": {
        "classmap": [
        "app/commands",
            "app/controllers",
            "app/models",
            "app/database/migrations",
            "app/database/seeds",
            "app/tests/TestCase.php",
        ],
        "psr-0": {
            "Custom": "app/custom"
        }
    }
  4. Open the command line and run dump-autoload on Composer:

    php composer.phar dump-autoload
    
  5. Now we can call that class by using its namespace. For example, if we create a route:

    Route::get('shape', function()
    {
        $shape = new Custom\Shapes\MyShapes;
        return $shape->triangle();
    });

How it works...

Namespaces are a powerful addition to PHP, and they allow our classes to be used without us having to worry about their class names interfering with other class names. By autoloading namespaces in Laravel, we could create a complex group of classes and never have to worry about class names conflicting with other namespaces.

For our purposes, we're loading the custom class through composer, and the PSR-0 standard of autoloading.

There's more...

To further extend the use of our namespaced class, we could use the IoC to bind it to our app. More information can be found in the Laravel documentation at http://laravel.com/docs/ioc.

See also

  • The Using Autoloader to map a class name to its file recipe

Left arrow icon Right arrow icon

Key benefits

  • Install and set up a Laravel application and then deploy and integrate third parties in your application
  • Create a secure authentication system and build a RESTful API
  • Build your own Composer Package and incorporate JavaScript and AJAX methods into Laravel

Description

When creating a web application, there are many PHP frameworks from which to choose. Some are very easy to set up, and some have a much steeper learning curve. Laravel offers both paths. You can do a quick installation and have your app up-and-running in no time, or you can use Laravel's extensibility to create an advanced and fully-featured app.Laravel Application Development Cookbook provides you with working code examples for many of the common problems that web developers face. In the process, it will also allow both new and existing Laravel users to expand their knowledge of the framework.This book will walk you through all aspects of Laravel development. It begins with basic set up and installation procedures, and continues through more advanced use cases. You will also learn about all the helpful features that Laravel provides to make your development quick and easy. For more advanced needs, you will also see how to utilize Laravel's authentication features and how to create a RESTful API.In the Laravel Application Development Cookbook, you will learn everything you need to know about a great PHP framework, with working code that will get you up-and-running in no time.

What you will learn

Set up a virtual host and development environment in Apache Set up a user authentication system Use the RESTful controllers Debug and profile your application Store and retrieve content from the cloud Use the Artisan command-line tool Integrate JavaScript and jQuery into your Laravel app Write unit tests for Laravel

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Buy Now

Product Details


Publication date : Oct 25, 2013
Length 272 pages
Edition : 1st Edition
Language : English
ISBN-13 : 9781782162827
Category :
Languages :

Table of Contents

18 Chapters
Laravel Application Development Cookbook Chevron down icon Chevron up icon
Credits Chevron down icon Chevron up icon
About the Author Chevron down icon Chevron up icon
About the Reviewers Chevron down icon Chevron up icon
www.PacktPub.com Chevron down icon Chevron up icon
Preface Chevron down icon Chevron up icon
Setting Up and Installing Laravel Chevron down icon Chevron up icon
Using Forms and Gathering Input Chevron down icon Chevron up icon
Authenticating Your Application Chevron down icon Chevron up icon
Storing and Using Data Chevron down icon Chevron up icon
Using Controllers and Routes for URLs and APIs Chevron down icon Chevron up icon
Displaying Your Views Chevron down icon Chevron up icon
Creating and Using Composer Packages Chevron down icon Chevron up icon
Using Ajax and jQuery Chevron down icon Chevron up icon
Using Security and Sessions Effectively Chevron down icon Chevron up icon
Testing and Debugging Your App Chevron down icon Chevron up icon
Deploying and Integrating Third-party Services into Your Application Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Filter icon Filter
Top Reviews
Rating distribution
Empty star icon Empty star icon Empty star icon Empty star icon Empty star icon 0
(0 Ratings)
5 star 0%
4 star 0%
3 star 0%
2 star 0%
1 star 0%

Filter reviews by


No reviews found
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.