Learning Laravel 4 Application Development

By Hardik Dangar
  • Instant online access to over 7,500+ books and videos
  • Constantly updated with 100+ new titles each month
  • Breadth and depth in over 1,000+ technologies
  1. Welcome to the World of Laravel

About this book

Laravel 4 is a clean and classy framework for PHP web development. It attempts to ease the development of web applications by simplifying the common tasks required in the majority of web projects, such as authentication, routing, sessions, and caching.

"Learning Laravel 4 Application Development" uses a step-by-step approach to teach you how to build real-world web applications. You will learn how to create a web application from scratch as well as how to create and use packages to build reusable components to be used in your projects.

This book begins by familiarizing you with MVC concepts as well as the Laravel 4 framework. From there, it moves on to the creation of the frontend and backend of your web application. As you progress through the book, you will learn how you can authenticate users as well as develop RESTful APIs. You will also learn how to configure, optimize, and secure your applications. Lastly, it teaches you how to deploy your applications using different approaches like Git, FTP, and SSH.

Laravel 4 Application Development will teach you everything you need to know to create accessible real-world web applications quickly and efficiently.

Publication date:
December 2013
Publisher
Packt
Pages
256
ISBN
9781783280575

 

Chapter 1. Welcome to the World of Laravel

In this chapter we are going to look at what MVC is and how it fits in web development. We will also look into some of the unique features of the Laravel framework, and we will see later what Laravel 4 offers us and how it is helpful to the developers.

There comes a time in every developer's life where you really want to change the way you work. You want to organize your code; you really care about how you are dividing things and try to refactor your code. You try to learn advanced patterns so that you can manage things, and as you move project-by-project, you develop a framework around your code, which you will use each time you create a new project.

You are beginning to realize there are other options too such as Frameworks. Frameworks are developed by the community, and you start to explore them and realize that there are some really good patterns. You also realize that a lot of the grunt work, which you have to do at the time of project initiation, has been done in the framework so that you can enjoy the experience of coding. You think you were stupid enough to not use this in your projects in the first place. You start thinking about objects, classes, patterns, and procedures.

Then it strikes to you, the moment of truth, and you decide to put yourself in the shoes of the framework. This is where this book helps you by guiding you step-by-step through the real-world application development via Laravel 4 Framework. I have chosen to walk you carefully through the real-world application development where scopes change, and you have to be ready for constantly changing your code. I will show you how you can effectively use Laravel to minimize the impact of changes and how you can develop applications that take away the pain you feel as a developer when changes constantly evolve in your application.

 

Landing yourself into the MVC world


When you look around in today's development world, you can find MVC everywhere. Ruby on Rails, ASP.NET, and PHP Frameworks such as CakePHP and Code Igniter all are using it. So what is it that makes MVC such an important part of all these frameworks?

The answer is Separation of Logic from your representation layer (Views/HTML). MVC allows you to write the code that can be divided on the basis of three things:

  • Model: Models are the way by which you can interact with data. It's a layer between your data and your application. Data can be in the database systems such as MySQL or MSSQL or simple Excel or XML files.

  • Views: Views are the visual representation of your application. Views allow us to write our presentation layer from our business logic.

  • Controller: Controller is a link between your Model and Views. The primary responsibility of a Controller is to handle requests and pass data from Model to Views.

The way MVC gives you the structure you can actually create separate views for single models, that is, if you are creating an e-commerce site, think of a products page. It can have multiple views such as the Product List View or Product Gallery View. In the MVC world, you will create one model for your product table and via that one model you can generate multiple views.

In a typical MVC web framework, you will find that Controllers handle user request and user data validation and business logic, Models represent data, and Views generate output data. Here is a Laravel framework example of our product's Controller, Model, and View:

Tip

Downloading the example code

You can download the example code files for all Packt books you have purchased from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

The code example for products Controller is as follows:

class ProductsController extends BaseController{

  public function listIndex()
  {
    $products = Products::all();
    return View::make('products', compact('products') );
  }

  public function galleryIndex()
  {
    $products = Products::all();
    return View::make('products_gallery', compact('products') );
  }
}

Here, the Products Controller executes the function based on the URI route. For example, if the route is http://sample.com/list, it will execute the listIndex function which will get all products via the Products Model defined as follows:

The code example for products Model is as follows:

Class Products extends Eloquent {}

The code example for gallery View is as follows:

<ul>
  @foreach ($products as $product)
   <li><img src="{{ $product->img }}"  >{{ $product->name }}</li>
  @endforeach
</ul>

The preceding view is for the product gallery view. We are iterating the products array and displaying it on the gallery View:

The code example for list View is as follows:

<div>
  @foreach ($products as $product)
    <img src="{{ $product->img }}"  >
    <span>{{ $product->name }}</span>
  @endforeach
</div>

The preceding view is for the product list view. We are iterating the products array and displaying it on the List view.

Now, if the client asks for changing the order of products in the descending order after six months, all we have to do is change the code we are using to fetch this data, and we will know that we have a fixed Controller for our products. We can then instantly recognize the place where we would have to make the change instead of scanning hundreds of files. If you want to change the look of site, you can just change Views. So, MVC provides us a structure that is easily recognizable as well as we know that when we change things, it will not affect other portions of our web pages.

 

Why Laravel 4 is awesome! And why it must be your next framework


The philosophy of Laravel's creator Taylor Otwell about Laravel is that:

Development should be a creative experience that you enjoy, not something that is painful.

The framework reflects that Laravel is a simple and elegant framework for PHP web development with expressive and artistic syntaxes. But there is more to Laravel 4. It is one of the few frameworks that have implemented Composer and in such a way that it gives you full control over what you want to choose in your framework. Let's review what has changed in the PHP community and how Laravel has adopted these changes in its significant Version 4.

The PHP community has been going through a revolution over the last few years. Those of you who are still not aware of the recent PHP development should read the guide phptherightway (http://www.phptherightway.com/) on what has changed in the recent PHP versions and how the community is creating an echo system that will change the way PHP is used in projects. One important thing that happened during these revolution is that a lot of framework developers met at php|tek in 2009 and formed the FIG (Framework Interoperability Group). The group formed standards that allow them to work together and share code even if frameworks are different. These standards are called PSR-0, PSR-1, PSR-2, and PSR-3. PSR- standards lay the foundation for Composer, which is a dependency management system for PHP. To know more about PSR standards, visit http://net.tutsplus.com/tutorials/php/psr-huh/.

So what is dependency? Dependency is a class or package we use in our code to achieve some specific tasks such as sending e-mails via PHPMailer or Swift Mailer. Now in this case, PHPMailer and Swift Mailer is a dependency of our application. Remember that a dependency can have another dependency, that is, Swift Mailer could be using some other third-party class or package that you are not aware of.

Composer

Composer is a dependency management tool for PHP. The most important thing about composer is that it can manage the dependency of your project dependencies; that is, if one of the libraries you are using in your project is dependent on two other libraries, you don't have to manually find and update anything to upgrade them. All three libraries can be updated via a single command, that is, Composer Update. Composer can manage dependency up to N level means all dependency of your project via single tool which is really powerful option to have when you are using lot of libraries. The other benefit is that it manages the auto load file, which will include all your dependencies. So you don't have to remember all paths to your dependencies and include each of them on every file of your project, just include the autoload file provided by composer.

So what is it that makes Laravel 4 stand out from other frameworks? We will discuss these features as follows:

  • Composer ready: Composer is the way the PHP community is going and there are thousands (7,000 currently) of packages already available in the Composer package archive (https://packagist.org/). Laravel 4 was designed in such a way that it integrates Composer packages easily. Laravel 4 itself uses some of the Composer components such as Symphony2's HTTP package for routing in Laravel 4. Say you want to send an SMTP e-mail with attachments. Download a Swift Mailer component with Composer, and you can directly use the Swift Mailer component anywhere in your project.

  • Interoperability: Laravel 4 is actually a mixture of different Composer components. All of these components are available in GitHub and all are 100 percent unit tested. Some of those components are carefully chosen by Taylor Otwell from very carefully crafted frameworks such as Symphony 2.

  • Laravel 4 gives you the power of choosing what you like. For example, you don't like the Mail component of Laravel, which is Swift Mailer actually, and you want to replace it with the PHPMailer component which you really like and is also Composer ready; thus, it will be a very easy operation to switch these two. You can swipe components as and when you need via the Composer and Laravel configuration.

  • You don't have to wait for months for updating that one feature you want for your database component. You can just simply update individual components via the composer update.

  • You can further develop core components yourself and use it in your projects without having to worry about the impact of changes in your framework.

Here are some of the unique features of Laravel:

  • Eloquent ORM: Laravel has one of the most advanced built-in ORMs called Eloquent that allows you to write database tables as objects and also allows you to interact with those objects. You can actually perform database operations without writing SQL queries. And it's also kind of unique because it allows you to maintain a relationship between tables, so you can perform lot of operations on multiple tables without writing long queries via objects.

  • Routes: Developers can write their logic either in Routers or Controllers. This can be handful when you have a small site, or you want to define static pages quickly. You would not need to write Controllers for every page of your site.

  • RESTful: Laravel 4 provides us with a unique way of creating RESTful APIs. You can define RESTful controllers via Laravel 4, and Controllers can have predefined methods to receive requests via GET, PUT, DELETE, POST, and UPDATE. We will see this in later chapters in detail when we build RESTful APIs with the help of Laravel 4.

  • Auto loading: Laravel 4 automatically loads all your dependencies such as libraries, packages, and Models. You don't have to manually load anything. Laravel 4 is smart about anything you use in your code since it will automatically load that class or library when you use it.

  • IOC containers: An IOC container is Laravel's way to manage independent components and provide a unique way to control them via a single API.

  • Migrations: Most of PHP fameworks take migrations, which is version management for your database. Laravel 4 has introduced migration with DB Seeds, which allows you to manage your database version as well as add some seed data as and when you need.

  • Pagination: Laravel 4 makes pagination breeze by, giving you a powerful library that allows you to write your pagination in simply three lines, which in other frameworks or a manual code would take hundreds of line of the code. We will see this in later chapters in detail when we build our application.

  • Unit testing: Laravel Framework was built with unit testing in mind. The framework itself provides unit tests for all of its components, and that's one of the reasons it's very stable as well as fast paced as constant changes can be tested via unit tests. You can also add your unit tests directly just like you write application classes. It allows various features such as seeding database from unit test classes and custom session handling, so you can test pretty much everything for your application.

  • Artisan: Artisan is the command-line tool of Laravel that allows you to perform a lot of grunt tasks you would hate to do manually. Artisan can be used to create your basic Controller, Model, and View files directly via the command line. It can also build migrations which can be handy to manage your database schema. With Laravel 4, you can create your own commands and do useful stuff such as send pending mails to people, or repair database, or anything that may be required occasionally for your application. You can also create database seeds that will allow you to seed some data initially. Artisan can also run unit tests for your application. We will see all of this in detail during our application development.

  • Queues: Laravel 4 has this really nice feature that every web developer dreams of—Queues. Yes, you can queue your tasks in Laravel 4 and what's so amazing about it is that users don't have to wait anymore for very long tasks; like you are generating multipage PDF or sending a lot of e-mails. You can just queue your tasks, and it will get executed later without slowing down the process.

  • Events: Laravel 4 provides events and you can hook your code into application-specific Laravel events. It's one of the features that really help developers. You can also create custom events for your application, or you can hook into Laravel 4 application-specific events such as Laravel.log, Laravel.query event.

I believe Laravel's features make a huge difference in how easy it is to write reusable, maintainable code. It is one of the major aspects of any framework. Laravel provides us with a base platform, which removes us from all cumbersome tasks and gives us a clean syntax. It also includes awesome tools to develop our project in such a way that we can enjoy the whole experience of doing it as a developer. Laravel 4 is the fresh air the PHP community needed after years of stalled development. Laravel reassembles new PHP 5.3 features and gives us many more features as a framework, which previously was not possible. And that's all about Laravel 4 features. I have just given the basic features in later chapters. We will see in detail the various features of Laravel 4 and explore how you can actually use them in your projects.

 

Summary


So we have learned how the MVC world works, what a composer is, and how it helps you in managing the dependencies of your application, and what Laravel 4 offers as an MVC framework and its unique features. In the next chapter let's dig deeper into the world of Laravel 4. If this excites you, let's begin the journey of Laravel 4.

About the Author

  • Hardik Dangar

    Hardik Dangar is co-founder of Sphere Rays Technolabs Pvt. Ltd. His primary focus has been on web-based ERP systems for the last six years. Lately, he has been working with a few of the key startups to shape their core ideas into architectural development and implementation of projects from inception. He can be found on Google+ developer communities and IRC channels of various frameworks helping people and building communities.

    Browse publications by this author
Book Title
Access this book, plus 7,500 other titles for FREE
Access now