This title was written for Laravel version 4. If you're looking for material on the latest version of Laravel, then please check out Code Smart.
Laravel is a framework for the PHP programming language. While PHP is known to have a less than desirable syntax, it is easy to use, easy to deploy, and can be found powering many of the modern web sites you use day to day. Laravel not only provides useful shortcuts, tools, and components to help you achieve success with all of your web based projects, but it also aims to fix some of PHP's flaws.
Laravel has a beautiful, semantic, and creative syntax that allows it to stand out among a large number of frameworks available for the language. This makes PHP a joy to use, without sacrificing power and efficiency. Laravel is a great choice for amateur projects and enterprise solutions alike, and whether you are a seasoned pro with the language, or a newcomer, Code Bright will help you turn the ideas you have into fully functional web applications.
Let's have a quick look at the requirements for both the framework and this book.
Requirements
- A Computer Reading is great, but you will learn more from playing with the examples that you find in the book.
- A Webserver Laravel needs a web server. It doesn't matter which one you use but I find the majority of the community use either Apache or Nginx and doing the same will make it much easier to find support if needed.
- PHP: Hypertext Preprocessor 5.3 or greater
Laravel is a PHP framework, it requires the PHP programming language. Trust me you are going to need this one. Since Laravel uses some modern features of the language you will also need version 5.3.7 or greater. You can find out the PHP version used by most web servers by typing
php -v
at the console, or using thephpinfo()
method. - A Database Server
While not a requirement of the framework, many of the examples in the book interact with a database. For this reason I would recommend setting up a database server supported by the PDO connector. While I would recommend using the flexible and free
MySQL
by Su.. Oracle, other popular database servers include SQL Server, Postgres and SQLite. - A Text Editor You will need this to play with the examples found within the book. I highly recommend Sublime Text 2, and while it's not free, it is extremely sexy. There are however millions of editors and IDEs available, find one that suits the way you work.
Now before we can start working on our Laravel projects, we must first download a copy of the framework.
Installation
I’m not really sure if installation is the right title for this section. However, I couldn’t really think of anything better.
You see, Laravel has a Github repository that acts as a kind of ‘template’ for your new Laravel application. Let’s copy that down to our local machine.
We will use git to ‘clone’ the repository down to a folder on our development web server. Here is the command.
git clone https://github.com/laravel/laravel.git my_project
Now you will have a template application for Laravel within the my_project
folder. You might find others referring to this template as the ‘app package’. This package will contain your entire application and the entire directory will likely be versioned.
Some experienced Laravel users may remember a directory called laravel
which used to contain the files that would power the framework. We sometimes would refer to this as the frameworks ‘core’ files. Well this directory can no longer be found. Leveraging the power of Composer, the core files for the framework now exist as a separate package that is a dependency of our template package.
Let’s take a look at the composer.json
file within our my_project
directory to see what’s new.
{
"require": {
"laravel/framework": "4.0.*"
},
"autoload": {
"classmap": [
"app/commands",
"app/controllers",
"app/models",
"app/database/migrations",
"app/database/seeds",
"app/tests/TestCase.php"
]
},
"scripts": {
"post-update-cmd": "php artisan optimize"
},
"minimum-stability": "dev"
}
Note that the versions of the dependencies may have changed since this section was last updated. The result however, will remain the same.
Our application package depends only upon the laravel/framework
package, which contains all of the components needed to power your application. This composer.json
file is ours. It is for our application and we may edit it however we please. However, some sensible defaults have been provided for you. I also wouldn’t recommend removing the laravel/framework
package. Very bad things will happen.
Right now we only have a template. Let’s run composer install
to install the frameworks core.
Loading composer repositories with package information
Installing dependencies
- Installing doctrine/lexer (dev-master bc0e1f0)
Cloning bc0e1f0cc285127a38c6c8ea88bc5dba2fd53e94
- Installing doctrine/annotations (v1.1)
Loading from cache
... Many more packages here. ...
- Installing ircmaxell/password-compat (1.0.x-dev v1.0.0)
Cloning v1.0.0
- Installing swiftmailer/swiftmailer (dev-master e77eb35)
Cloning e77eb358a1aa7157afb922f33e2afc22f6a7bef2
- Installing laravel/framework (dev-master 227f5b8)
Cloning 227f5b85cc2201b6330a8f7ea75f0093a311fe3b
predis/predis suggests installing ext-phpiredis (Allows faster serialization and deserialization of the Redis protocol)
symfony/translation suggests installing symfony/config (2.2.*)
symfony/translation suggests installing symfony/yaml (2.2.*)
symfony/routing suggests installing symfony/config (2.2.*)
symfony/routing suggests installing symfony/yaml (2.2.*)
symfony/event-dispatcher suggests installing symfony/dependency-injection (2.2.*)
symfony/http-kernel suggests installing symfony/class-loader (2.2.*)
symfony/http-kernel suggests installing symfony/config (2.2.*)
symfony/http-kernel suggests installing symfony/dependency-injection (2.2.*)
symfony/debug suggests installing symfony/class-loader (~2.1)
monolog/monolog suggests installing mlehner/gelf-php (Allow sending log messages to a GrayLog2 server)
monolog/monolog suggests installing ext-amqp (Allow sending log messages to an AMQP server (1.0+ required))
monolog/monolog suggests installing ext-mongo (Allow sending log messages to a MongoDB server)
monolog/monolog suggests installing doctrine/couchdb (Allow sending log messages to a CouchDB server)
monolog/monolog suggests installing raven/raven (Allow sending log messages to a Sentry server)
Writing lock file
Generating autoload files
Once again, the package versions may have changed, but the result will still be the same.
Well that sure was a long list of packages! What are they all for? Well, you see, Laravel leverages the power of open source, and the wealth of packages that exist on Composer. These packages are dependencies of the framework itself.
You should definitely take after Laravel and check out the packages that are listed on the Packagist website. There’s no point in re-inventing the wheel when it comes to boilerplate code.
Since you have read the Composer chapter, you will now know that the core files for Laravel have been installed to the vendor folder. You don’t really want to version your dependencies along the code, so Laravel has provided a sample .gitignore
file to ignore the vendor
s folder, along with a few other sensible defaults.
We’re almost done setting up our Laravel development environment. Only one topic remains. How to set up your webserver.
Web Server Configuration
This section was always going to be a difficult one to write. You see, everyone has a slightly different setup, and there are a number of different web servers available.
So here’s what I’m going to do. I will cover the basics of where the web server needs to be pointed. I will also provide some sample configurations for common web servers. They will however be very generic, and require many tweaks to fit into every sithation. Still, you can’t say I didn’t try!
Let’s have a look at what the goal is here. Laravel has a directory called public
which contains its bootstrap code. This code used to launch the framework, and handle all requests to your application.
The public
folder also contains all of your public assets, such as JavaScript, CSS and images. Essentially, anything that can be accessed via a direct link should exist within the public
directory.
What does this mean for our web server configuration? Well our first task is to make sure that the web server is looking in the right place. We need to edit its configuration so that it will be looking at the public
directory, and not the root of our project.
The next task will be to let the web server know how to handle pretty URLs.
I chose a really cool domain name, don’t I already have a pretty URL?
Sadly, that’s not quite how it works. Life isn’t all cakes and pies you know? The Laravel bootstrap exists within a file called index.php
within the public
folder. All requests to the framework are going to go through this file. This means that by default, the URL to our guestbook page will look like this:
http://islifeallcakesandpies.com/index.php/guestbook
Our websites users don’t really need to know that everything is being directed through index.php
. It’s also not a great feature for search engine optimisation. For that reason our web server should be configured to remove the index.php
from the URL, leaving only the ‘pretty’ segment remaining. Normally this is achieved by a piece of config crafted by a regular expression wizard.
Let’s now take a look at some sample web server configurations that will allow us to achieve the goals mentioned above. Once again I must remind you that these configurations are to be used as rough guidance. For more detailed information on server configuration I would recommend visiting the documentation for the web server that you have chosen.
Let’s start with nginx.
Nginx
Nginx, pronounced ‘engine-X’, is a wonderful web server that I have recently started using. For me the choice was simple. It performed much faster than apache, and didn’t require XML(ish) configuration. It all made sense to me.
On a Debian based linux distribution, like Ubuntu, you can install nginx and PHP by running the following command.
sudo apt-get install nginx php5-fpm
The second package is PHP-FPM, a FastCGI module that will allow nginx to execute PHP code.
On Mac these packages are available on Macports. The required packages can be installed with the following command.
sudo port install php54-fpm nginx
Your Nginx site configuration files are normally located at /etc/nginx/sites-enabled
. Here is a template that you can use to setup a new site.
server {
# Port that the web server will listen on.
listen 80
# Host that will serve this project.
server_name app.dev
# Useful logs for debug.
access_log /path/to/access.log;
error_log /path/to/error.log;
rewrite_log on;
# The location of our projects public directory.
root /path/to/our/public;
# Point index to the Laravel front controller.
index index.php;
location / {
# URLs to attempt, including pretty ones.
try_files $uri $uri/ /index.php?$query_string;
}
# Remove trailing slash to please routing system.
if (!-d $request_filename) {
rewrite ^/(.+)/$ /$1 permanent;
}
# PHP FPM configuration.
location ~* \.php$ {
fastcgi_pass unix:/var/run/php5-fpm.sock;
fastcgi_index index.php;
fastcgi_split_path_info ^(.+\.php)(.*)$;
include /etc/nginx/fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
}
# We don't need .ht files with nginx.
location ~ /\.ht {
deny all;
}
}
Now, not all web servers are going to be the same. This means that providing a generic configuration to suit all sithations would be an impossible task. Still, it’s enough to get you started.
I’ve shared the standard configurations used in this chapter on Github so that everyone can contribute to them. You can find them in the daylerees/laravel-website-configs repository.
While nginx is a great choice of web server, the Apache web server is also widely used. Let’s take a look at how to configure it.
Apache
The Apache web server can be installed on Debian based systems using the following command.
sudo apt-get install apache2 php5
Here’s an Apache VirtualHost configuration that will fit most sithations, feel free to contribute to the repository on github if any amendments are needed.
<VirtualHost *:80>
# Host that will serve this project.
ServerName app.dev
# The location of our projects public directory.
DocumentRoot /path/to/our/public
# Useful logs for debug.
CustomLog /path/to/access.log common
ErrorLog /path/to/error.log
# Rewrites for pretty URLs, better not to rely on .htaccess.
<Directory /path/to/our/public>
<IfModule mod_rewrite.c>
Options -MultiViews
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
</IfModule>
</Directory>
</VirtualHost>
Project Structure
I had a chapter in the previous book that covered the directory structure of the package, and where everything likes to live. I think there was a lot of value in this chapter, so I’d like to reiterate it along with the directory structure changes that have happened since Laravel 3.
This section of the getting started will assume that you have already ran composer install
on a fresh Laravel 4 project.
Project Root
Let’s start by taking a look at the root folder structure.
- app/
- bootstrap/
- vendor/
- public/
- .gitattributes
- .gitignore
- artisan
- composer.json
- composer.lock
- phpunit.xml
- server.php
Why don’t we have a run through these root items? Sounds like a great idea to me!
app
First up we have the app
directory. App is used to provide a default home for all of your projects custom code. This includes classes that provide application functionality, config files, and more. The app
folder is quite important, so rather than giving it a poor summary in a single paragraph, we will cover it in detail at the end of this section. For now, just know this is where your project files live.
bootstrap
- autoload.php
- paths.php
start.php
The bootstrap directory contains a few files that relate to the startup procedures of the framework. The
autoload.php
file contains most of these procedures, and should only be edited by experienced Laravel users.The
paths.php
file builds an array of the common filesystem paths that are used by the framework. If for some reason you decide to alter the directory structure of the framework packages, you may need to alter the contents of this file to reflect your changes.The
start.php
file contains more startup procedures for the framework. I don’t want to dig into these in detail right now as that may cause unnecessary confusion. Instead you should probably take note that frameworkenvironments
can be set here. If you don’t know what the environments are used for then don’t worry. We will cover that later!
Simply put, the contents of the bootstrap
directory should only be edited by experienced Laravel users who need to alter the shape of the framework on the filesystem. If you are new to Laravel, then just ignore it for now, but don’t delete it! Laravel needs this directory to function.
vendor
The vendor
directory contains all of the composer packages that are used by your application. This, of course, includes the Laravel framework package. For more information about this directory please refer back to the Composer primer chapter.
public
- packages/
- .htaccess
- favicon.ico
- index.php
- robots.txt
The public
directory should be the only web facing directory of a Laravel application. It’s normally where your assets such as CSS, Javascript files and images will live. Let’s have a closer look at the contents.
The packages
directory will be used to contain any assets that need to be installed by third party packages. They are kept in a separate directory so that they don’t conflict with our applications own assets.
Laravel 4 ships with a standard .htaccess
file for the Apache web server. It contains some standard configuration directives that will make sense for most users of the framework. If you use an alternative web server you can either ignore this file or delete it.
By default, web browsers will try to look at the directory index of a site to find a favicon.ico
file. This is the file that controls the little 16 x 16px image that is displayed in your browsers tabs. The trouble is, when this file doesn’t exist the web server likes to complain about it. This causes unnecessary log entries. To counteract this problem Laravel has provided a default, blank favicon.ico
file, which can be later replaced if so desired.
The index.php
file is the Laravel framework front controller. It’s the first file that the web server hits when a request is received from the browser. This is the file that will launch the framework bootstrap and start the ball rolling so to speak. Don’t delete this file, it wouldn’t be a good idea!
Laravel has included standard robots.txt
file that allows all hosts by default. This is for your convenience, feel free to alter this file as necessary.
.gitattributes
Laravel has provided some default Git version control configuration for use out of this box. Git is currently the most popular choice of version control. If you don’t intend to version your project with Git then feel free to remove these files.
.gitignore
The .gitignore
file contains some defaults to inform the Git version control system of which folders should not be versioned. You should note that this also includes both the vendor
directory and the application storage
directory. The vendor
directory has been included to prevent third party packages being versioned.
The composer.lock
has also been included, although you may wish to remove this entry, and version your lock file to allow for your production environment to install the exact same dependency versions as your development environment. You will find more on this topic within the Composer primer chapter.
artisan
The artisan
file is an executable which is used to execute the Artisan command line interface for Laravel. Artisan contains a number of useful commands to provide shortcuts or additional functionality to the framework. Its commands will be covered in detail in a later chapter.
composer.json and composer.lock
Both the composer.json
and composer.lock
file, contain information about the composer packages used by this project. Once again, you can find more information about these files within the Composer primer chapter.
phpunit.xml
The phpunit.xml
file provides a default configuration for the PHP Unit testing framework. It will handle the loading of composer dependencies, and execute any tests located in the app/tests
folder. Information on testing with Laravel will be revealed in a later chapter, stay tuned!
server.php
The server.php
file is used by PHP's built in webserver to create an easy means of executing your web applications. Simply use the artisan serve
command to launch a local development webserver for the application.
The Application Directory
Here is where your application will take its shape. It is the directory in which you will spend most of your time. For that reason, why don’t we get better acquainted with it?
- commands/
- config/
- controllers/
- database/
- lang/
- models/
- start/
- storage/
- tests/
- views/
- filters.php
- routes.php
commands
The commands directory contains any custom artisan command line interface commands that are required by your application. You see the Artisan CLI not only provides default functionality to help you build your project, but you may also create custom commands to do your bidding.
config
The configuration for both the framework and your application are kept within this directory. Laravel’s configuration exists as a set of PHP files containing key-value arrays. This directory will also contain sub directories which allow for different configurations to be loaded in different environments.
controllers
As the name suggests, this directory will hold your controllers. Controllers can be used to provide application logic, and to glue the separate parts of your application together. This directory has been added to the default composer.json
as a classmap autoload location for your convenience.
database
Should you choose to use a database as a method of long term storage, then this directory will be used to hold the files that will create your database schema, and methods for seeding it with sample data. The default SQLite database is also located in this directory.
lang
The lang
directory contains PHP files with arrays of strings that can be used to provide localisation support to your application. Sub folders named by region allow for string files to exist for multiple languages.
models
The models directory will contain your models. Surprised? Models are used to represent your business model, or provide interaction with storage. Confused? Don’t worry. We will cover models in detail in a later chapter. Know that a User
model has been provided for you to enable application authentication ‘out of the box’. Like the controllers
directory, this has been added to the classmap autoload section of the default composer.json
.
start
Where the bootstrap
directory contains the startup procedures that belong to the framework, the start
directory contains startup procedures that belong to your application. As always, some sensible defaults have been provided for you.
storage
When Laravel needs to write anything to disk, it does so within the storage
directory. For this reason your web server must be able to write to this location.
tests
The tests
directory will contain all of the unit and acceptance tests for your application. The default PHP Unit configuration that has been included with Laravel, will look for tests within this directory by default.
views
The views directory is used to contain the visual templates for your application. A default hello
view has been provided for your convenience.
filters.php
The filters.php
file is used to contain the route filters for your application. You will learn more about filters in a future chapter.
routes.php
The routes file contains all of the routes for your application. You don’t know what routes are? Well, let’s not waste any more time then. Onwards to the next chapter!
My books are available online for free to encourage learning. However, if you'd like for me to keep writing, then please consider buying a digital copy over at Leanpub.com.
It's available in PDF, ePub, and Kindle format, and contains a bunch of extras that you won't find on the site. I have a full-time job, and I write my books in my spare time. Please consider buying a copy so that I can continue to write new books from the comfort of my sofa!