## 1. Project Overview & Quickstart (errors/index)

# Technical Documentation: errors/index

> ℹ️ **Provenance:** Multi-Tier Ingestion · [CodeWiki Reference](https://codewiki.google/github.com/errors/index)

# index

### Agent Skills & Rules
- Discovered 21 agent rule(s) and prompt configurations.



--- METRICS ---
- Files Extracted: 1
- Estimated Token Budget: ~23 tokens
- Canonical Reference: https://codewiki.google/github.com/errors/index


## 2. Official Technical Reference & Guides (errors/docs)

## File: artisan.md

# Artisan CLI

- [Introduction](#introduction)
- [Usage](#usage)

<a name="introduction"></a>
## Introduction

Artisan is the name of the command-line interface included with Laravel. It provides a number of helpful commands for your use while developing your application. It is driven by the powerful Symfony Console component.

<a name="usage"></a>
## Usage

To view a list of all available Artisan commands, you may use the `list` command:

**Listing All Available Commands**

	php artisan list

Every command also includes a "help" screen which displays and describes the command's available arguments and options. To view a help screen, simply precede the name of the command with `help`:

**Viewing The Help Screen For A Command**

	php artisan help migrate

You may specify the configuration environment that should be used while running a command using the `--env` switch:

**Specifying The Configuration Environment**

	php artisan migrate --env=local

You may also view the current version of your Laravel installation using the `--version` option:

**Displaying Your Current Laravel Version**

	php artisan --version

---

## File: cache.md

# Cache

- [Configuration](#configuration)
- [Cache Usage](#cache-usage)
- [Database Cache](#database-cache)

<a name="configuration"></a>
## Configuration

Laravel provides a unified API for various caching systems. The cache configuration is located at `app/config/cache.php`. In this file you may specify which cache driver you would like used by default throughout your application. Laravel supports popular caching backends like [Memcached](http://memcached.org) and [Redis](http://redis.io) out of the box.

The cache configuration file also contains various other options, which are documented within the file, so make sure to read over these options. By default, Laravel is configured to use the `file` cache driver, which stores the serialized, cached objects in the filesystem. For larger applications, it is recommended that you use an in-memory cache such as Memcached or APC.

<a name="cache-usage"></a>
## Cache Usage

**Storing An Item In The Cache**

	Cache::put('key', 'value', $minutes);

**Retrieving An Item From The Cache**

	$value = Cache::get('key');

**Retrieving An Item Or Returning A Default Value**

	$value = Cache::get('key', 'default');

	$value = Cache::get('key', function() { return 'default'; });

**Storing An Item In The Cache Permanently**

	Cache::forever('key', 'value');

Sometimes you may wish to retrieve an item from the cache, but also store a default value if the requested item doesn't exist. You may do this using the `Cache::remember` method:

	$value = Cache::remember('users', $minutes, function()
	{
		return DB::table('users')->get();
	});

You may also combine the `remember` and `forever` methods:

	$value = Cache::rememberForever('users', $minutes, function()
	{
		return DB::table('users')->get();
	});

Note that all items stored in the cache are serialized, so you are free to store any type of data.

**Removing An Item From The Cache**

	Cache::forget('key');

<a name="database-cache"></a>
## Database Cache

When using the `database` cache driver, you will need to setup a table to contain the cache items. Below is an example `Schema` declaration for the table:

	Schema::create('cache', function($t)
	{
		$t->string('key')->unique();
		$t->text('value');
		$t->integer('expiration');
	});

---

## File: commands.md

# Artisan Development

- [Introduction](#introduction)
- [Building A Command](#building-a-command)
- [Registering Commands](#registering-commands)
- [Calling Other Commands](#calling-other-commands)

<a name="introduction"></a>
## Introduction

In addition to the commands provided with Artisan, you may also build your own custom commands for working with your application. You may store your custom commands in the `app/commands` directory; however, you are free to choose your own storage location as long as your commands can be autoloaded based on your `composer.json` settings.

<a name="building-a-command"></a>
## Building A Command

### Generating The Class

To create a new command, you may use the `command:make` Artisan command, which will generate a command stub to help you get started:

**Generate A New Command Class**

	php artisan command:make FooCommand

By default, generated commands will be stored in the `app/commands` directory; however, you may specify custom path or namespace:

	php artisan command:make FooCommand --path="app/classes" --namespace="Classes"

### Writing The Command

Once your command is generated, you should fill out the `name` and `description` properties of the class, which will be used when displaying your command on the `list` screen.

The `fire` method will be called when your command is executed. You may place any command logic in this method.

### Arguments & Options

The `getArguments` and `getOptions` methods are where you may define any arguments or options your command receives. Both of these methods return an array of commands, which are described by a list of array options.

When defining `arguments`, the array definition values represent the following:

	array($name, $mode, $description, $defaultValue)

The argument `mode` may be any of the following: `InputArgument::REQUIRED` or `InputArgument::OPTIONAL`.

When defining `options`, the array definition values represent the following:

	array($name, $shortcut, $mode, $description, $defaultValue)

For options, the argument `mode` may be: `InputOption::VALUE_REQUIRED`, `InputOption::VALUE_OPTIONAL`, `InputOption::VALUE_IS_ARRAY`, `InputOption::VALUE_NONE`.

The `VALUE_IS_ARRAY` mode indicates that the switch may be used multiple times when calling the command:

	php artisan foo --option=bar --option=baz

The `VALUE_NONE` option indicates that the option is simply used as a "switch":

	php artisan foo --option

### Retrieving Input

While you command is executing, you will obviously need to access the values for the arguments and options accepted by your application. To do so, you may use the `argument` and `option` methods:

**Retrieving The Value Of A Command Argument**

	$value = $this->argument('name');

**Retrieving All Arguments**

	$arguments = $this->argument();

**Retrieving The Value Of A Command Option**

	$value = $this->option('name');

**Retrieving All Options**

	$options = $this->option();

### Writing Output

To send output to the console, you may use the `info`, `comment`, `question` and `error` methods. Each of these methods will use the appropriate ANSI colors for their purpose.

**Sending Information To The Console**

	$this->info('Display this on the screen');

**Sending An Error Message To The Console**

	$this->error('Something went wrong!');

### Asking Questions

You may also use the `ask` and `confirm` methods to prompt the user for input:

**Asking The User For Input**

	$name = $this->ask('What is your name?');

**Asking The User For Confirmation**

	if ($this->confirm('Do you wish to continue? [yes|no]'))
	{
		//
	}

You may also specify a default value to the `confirm` method, which should be `true` or `false`:

	$this->confirm($question, true);

<a name="registering-commands"></a>
## Registering Commands

Once your command is finished, you need to register it with Artisan so it will be available for use. This is typically done in the `app/start/artisan.php` file. Within this file, you may use the `Artisan::add` method to register the command:

**Registering An Artisan Command**

	Artisan::add(new CustomCommand);

If your command is registered in the application [IoC container](/docs/ioc), you may use the `Artisan::resolve` method to make it available to Artisan:

**Registering A Command That Is In The IoC Container**

	Artisan::resolve('binding.name');

<a name="calling-other-commands"></a>
## Calling Other Commands

Sometimes you may wish to call other commands from your command. You may do so using the `call` method:

**Calling Another Command**

	$this->call('command.name', array('argument' => 'foo', '--option' => 'bar'));

---

## File: configuration.md

# Configuration

- [Introduction](#introduction)
- [Environment Configuration](#environment-configuration)

<a name="introduction"></a>
## Introduction

All of the configuration files for the Laravel framework are stored in the `app/config` directory. Each option in every file is documented, so feel free to look through the files and get familiar with the options available to you.

Sometimes you may need to access configuration values at run-time. You may do so using the `Config` class:

**Accessing A Configuration Value**

	Config::get('app.timezone');

Notice that "dot" style syntax may be used to access values in the various files. You may also set configuration values at run-time:

**Setting A Configuration Value**

	Config::set('database.default', 'sqlite');

<a name="environment-configuration"></a>
## Environment Configuration

It is often helpful to have different configuration values based on the environment the application is running in. For example, you may wish to use a different cache driver on your local development machine than on the production server. It is easy to accomplish this using environment based configuration.

Simply create a folder within the `config` directory that matches your environment name, such as `local`. Next, create the configuration files you wish to override and specify the options for that environment. For example, to override the cache driver for the local environment, you would create a `cache.php` file in `app/config/local` with the following content:

	<?php

	return array(

		'driver' => 'file',

	);

Notice that you do not have to specify _every_ option that is in the base configuration file, but only the options you wish to override. The environment configuration files will "cascade" over the base files.

Next, we need to instruct the framework how to determine which environment it is running in. The default environment is always `production`. However, you may setup other environments within the `start.php` file at the root of your installation. In this file you will find an `$app->detectEnvironment` call. The array passed to this method is used to determine the current environment. You may add other environments and machine names to the array as needed.

---

## File: contributing.md

# Contributing To Laravel

- [Introduction](#introduction)
- [Pull Requests](#pull-requests)
- [Coding Guidelines](#coding-guidelines)

<a name="introduction"></a>
## Introduction

Laravel is free, open-source software, meaning anyone can contribute to its development and progress. Laravel source code is currently hosted on [Github](http://github.com), which provides an easy method for forking the project and merging your contributions.

<a name="pull-requests"></a>
## Pull Requests

The pull request process differs for new features and bugs. Before sending a pull request for a new feature, you should first create an issue with `[Proposal]` in the title. The proposal should describe the new feature, as well as implementation ideas. The proposal will then be reviewed and either approved or denied. Once a proposal is approved, a pull request may be created implementing the new feature. Pull requests which do not follow this guideline will be closed immediately.

Pull requests for bugs may be sent without creating any proposal issue. If you believe that you know of a solution for a bug that has been filed on Github, please leave a comment detailing your proposed fix.

### Feature Requests

If you have an idea for a new feature you would like to see added to Laravel, you may create an issue on Github with `[Request]` in the title. The feature request will then be reviewed by a core contributor.

<a name="coding-guidelines"></a>
## Coding Guidelines

Laravel follows the [PSR-0](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-0.md) and [PSR-1](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-1-basic-coding-standard.md) coding standards. In addition to these standards, below is a list of other coding standards that should be followed:

- Namespace declarations should be on the same line as `<?php`.
- Class opening `{` should be on the same line as the class name.
- Function and control structure opening `{` should be on a separate line.
- Always use `and` and `or`. Never use `&&` or `||`.
- Interface names are suffixed with `Interface` (`FooInterface`)

---

## File: controllers.md

# Controllers

- [Basic Controllers](#basic-controllers)
- [Controller Filters](#controller-filters)
- [Resource Controllers](#resource-controllers)

<a name="basic-controllers"></a>
## Basic Controllers

Instead of defining all of your route-level logic in a single `routes.php` file, you may wish to organize this behavior using Controller classes. Controllers can group related route logic into a class, as well as take advantage of more advanced framework features such as automatic [dependency injection](/docs/ioc).

Controllers are typically stored in the `app/controllers` directory, and this directory is registered in the `classmap` option of your `composer.json` file by default.

Here is an example of a basic controller class:

	class UserController extends BaseController {

		/**
		 * Show the profile for the given user.
		 */
		public function showProfile($id)
		{
			$user = User::find($id);

			return View::make('user.profile', ['user' => $user]);
		}

	}

All controllers should extend the `BaseController` class. The `BaseController` is also stored in the `app/controllers` directory, and may be used as a place to put shared controller logic. The `BaseController` extends the framework's `Controller` class. Now, We can route to this controller action like so:

	Route::get('user/{id}', 'UserController@showProfile');

If you choose to nest or organize your controller using PHP namespaces, simply use the fully qualified class name when defining the route:

	Route::get('foo', 'Namespace\FooController@method');

You may also specify names on controller routes:

	Route::get('foo', ['uses' => 'FooController@method', 'as' => 'name']);

> **Note:** After creating a new class, make sure to run `composer dump-autoload` from the command line. This will allow the framework to automatically load your class.

<a name="controller-filters"></a>
## Controller Filters

[Filters](/docs/routing#route-filters) may be specified on controller routes similar to "regular" routes:

	Route::get('profile', ['before' => 'auth', 'uses' => 'UserController@showProfile']);

However, you may also specify filters from within your controller:

	class UserController extends BaseController {

		/**
		 * Instantiate a new UserController instance.
		 */
		public function __construct()
		{
			$this->beforeFilter('auth');

			$this->beforeFilter('csrf', ['on' => 'post']);

			$this->afterFilter('log', ['only' => ['fooAction', 'barAction']]);
		}

	}

You may also specify controller filters inline using a Closure:

	class UserController extends BaseController {

		/**
		 * Instantiate a new UserController instance.
		 */
		public function __construct()
		{
			$this->beforeFilter(function()
			{
				//
			});
		}

	}

<a name="resource-controllers"></a>
## Resource Controllers

Resource controllers make it easier to build RESTful controllers around resources. For example, you may wish to create a controller that manages "photos" stored by your application. Using the `controller:make` command via the Artisan CLI and the `Route::resource` method, we can quickly create such a controller.

To create the controller via the command line, execute the following command:

	php artisan controller:make PhotoController

Now we can register a resourceful route to the controller:

	Route::resource('photo', 'PhotoController');

This single route declaration creates multiple routes to handle a variety of RESTful actions on the photo resource. Likewise, the generated controller will already have stubbed methods for each of these actions with notes informing you which URIs and verbs they handle.

**Actions Handled By Resource Controller**

Verb      | Path                  | Action
----------|-----------------------|--------------
GET       | /resource             | index
GET       | /resource/new         | create
POST      | /resource             | store
GET       | /resource/{id}        | show
GET       | /resource/{id}/edit   | edit
PUT/PATCH | /resource/{id}        | update
DELETE    | /resource/{id}        | destroy

Sometimes you may only need to handle a subset of the resource actions:

	php artisan controller:make PhotoController --only=index,show

	php artisan controller:make PhotoController --except=index

And, you may also specify a subset of actions to handle on the route:

	Route::resource('photo', 'PhotoController', ['only' => ['index', 'show']]);

---

## File: database.md

## Basic Database Usage

- [Configuration](#configuration)
- [Running Queries](#running-queries)
- [Accessing Connections](#accessing-connections)

<a name="configuration"></a>
## Configuration

Laravel makes connecting with databases and running queries extremely simple. The database configuration file is `app/config/database.php`. In this file you may define all of your database connections, as well as specify which connection should be used by default. Examples for all of the supported database systems are provided in this file.

Currently Laravel supports four database systems: MySQL, Postgres, SQLite, and SQL Server.

<a name="running-queries"></a>
## Running Queries

Once you have configured your database connection, you may run queries using the `DB` class.

**Running A Select Query**

	$results = DB::select('select * from users where id = ?', array(1));

The `select` method will always return an `array` of results.

**Running An Insert Statement**

	DB::insert('insert into users (id, name) values (?, ?)', array(1, 'Dayle'));

**Running An Update Statement**

	DB::update('update users set votes = 100 where name = ?', array('John'));

**Running A Delete Statement**

	DB::delete('delete from users');

> **Note:** The `update` and `delete` statements return the number of rows affected by the operation.

<a name="accessing-connections"></a>
## Accessing Connections

When using multiple connections, you may access them via the `DB::connection` method:

	$users = DB::connection('foo')->select(...);

---

## File: documentation.md

- Preface
    - [Introduction](/docs/introduction)
    - [Contributing](/docs/contributing)
- Getting Started
    - [Installation](/docs/installation)
    - [Configuration](/docs/configuration)
    - [Request Lifecycle](/docs/lifecycle)
    - [Routing](/docs/routing)
    - [Requests & Input](/docs/requests)
    - [Views & Responses](/docs/responses)
    - [Controllers](/docs/controllers)
    - [Errors & Logging](/docs/errors)
- Learning More
    - [Cache](/docs/cache)
    - [Events](/docs/events)
    - [IoC Container](/docs/ioc)
    - [Localization](/docs/localization)
    - [Mail](/docs/mail)
    - [Package Development](/docs/packages)
    - [Pagination](/docs/pagination)
    - [Queues](#)
    - [Security](/docs/security)
    - [Session](/docs/session)
    - [Unit Testing](/docs/testing)
    - [Validation](/docs/validation)
- Database
    - [Basic Usage](/docs/database)
    - [Query Builder](/docs/queries)
    - [Eloquent ORM](/docs/eloquent)
    - [Schema Builder](/docs/schema)
    - [Migrations & Seeding](/docs/migrations)
    - [Redis](/docs/redis)
- Artisan CLI
    - [Overview](/docs/artisan)
    - [Development](/docs/commands)
- Advanced Topics
    - [Architecture](#)

---

## File: eloquent.md

# Eloquent ORM

- [Introduction](#introduction)
- [Basic Usage](#basic-usage)
- [Insert, Update, Delete](#insert-update-delete)
- [Timestamps](#timestamps)
- [Relationships](#relationships)
- [Eager Loading](#eager-loading)
- [Inserting Related Models](#inserting-related-models)
- [Working With Pivot Tables](#working-with-pivot-tables)
- [Collections](#collections)
- [Accessors & Mutators](#accessors-and-mutators)
- [Mass Assignment](#mass-assignment)
- [Converting To Arrays / JSON](#converting-to-arrays-or-json)

<a name="introduction"></a>
## Introduction

The Eloquent ORM included with Laravel provides a beautiful, simple ActiveRecord implementation for working with your database. Each database table has a corresponding "Model" which is used to interact with that table.

Before getting started, be sure to configure a database connection in `app/config/database.php`.

<a name="basic-usage"></a>
## Basic Usage

To get started, create an Eloquent model. Models typically live in the `app/models` directory, but you are free to place them anywhere that can be auto-loaded according to your `composer.json` file.

**Defining An Eloquent Model**

	class User extends Eloquent {

		protected $table = 'users';

	}

Once a model is defined, you are ready to start retrieving and creating records in your table. Note that you will need to place `updated_at` and `created_at` columns on your table by default. If you do not wish to have these columns automatically maintained, set the `$timestamps` property on your model to `false`.

**Retrieving All Models**

	$users = User::all();

**Retrieving A Record By Primary Key**

	$user = User::find(1);

	var_dump($user->name);

> **Note:** All methods available on the [query builder](/docs/queries) are also available when querying Eloquent models.

**Querying Using Eloquent Models**

	$users = User::where('votes', '>', 100)->take(10)->get();

	foreach ($users as $user)
	{
		var_dump($user->name);
	}

Of course, you may also use the query builder aggregate functions.

**Eloquent Aggregates**

	$count = User::where('votes', '>', 100)->count();

<a name="insert-update-delete"></a>
## Insert, Update, Delete

To create a new record in the database from a model, simply create a new model instance and call the `save` method.

**Saving A New Model**

	$user = new User;

	$user->name = 'John';

	$user->save();

You may also use the `create` method to save a new model in a single line. The inserted model instance will be returned to you from the method:

**Using The Model Create Method**

	$user = User::create(['name' => 'John']);

To update a model, you may retrieve it, change an attribute, and use the `save` method:

**Updating A Retrieved Model**

	$user = User::find(1);

	$user->email = 'john@foo.com';

	$user->save();

You may also run updates as queries against a set of models:

	$affectedRows = User::where('votes', '>', 100)->update(['status' => 2]);

To delete a model, simply call the `delete` method on the instance:

**Deleting An Existing Model**

	$user = User::find(1);

	$user->delete();

Of course, you may also run a delete query on a set of models:

	$affectedRows = User::where('votes', '>', 100)->delete();

<a name="timestamps"></a>
## Timestamps

By default, Eloquent will maintain the `created_at` and `updated_at` columns on your database table automatically. Simply add these `datetime` columns to your table and Eloquent will take care of the rest. If you do not wish for Eloquent to maintain these columns, add the following property to your model:

**Disabling Auto Timestamps**

	class User extends Eloquent {

		protected $table = 'users';

		protected $timestamps = false;

	}

If you wish to customize the format of your timestamps, you may override the `freshTimestamp` method in your model:

**Providing A Custom Timestamp Format**

	class User extends Eloquent {

		public function freshTimestamp()
		{
			return time();
		}

	}

<a name="relationships"></a>
## Relationships

Of course, your database tables are probably related to one another. For example, a blog post may have many comments, or an order could be related to the user who placed it. Eloquent makes managing and working with these relationships easy. Laravel supports four types of relationships:

- [One To One](#one-to-one)
- [One To Many](#one-to-many)
- [Many To Many](#many-to-many)
- [Polymorphic Relations](#polymorphic-relations)

<a name="one-to-one"></a>
### One To One

A one-to-one relationship is a very basic relation. For example, a `User` model might have one `Phone`. We can define this relation in Eloquent:

**Defining A One To One Relation**

	class User extends Eloquent {

		public function phone()
		{
			return $this->hasOne('Phone');
		}

	}

The first argument passed to the `hasOne` method is the name of the related model. Once the relationship is defined, we may retrieve it using Eloquent's dynamic properties:

	$phone = User::find(1)->phone;

The SQL performed by this statement will be as follows:

	select * from users where id = 1

	select * from phones where user_id = 1

Take note that Eloquent assumes the foreign key of the relationship based on the model name. In this case, `User` model is assumed to use a `user_id` foreign key. If you wish to override this convention, you may pass a second argument to the `hasOne` method:

	return $this->hasOne('Phone', 'custom_key');

To define the inverse of the relationship on the `Phone` model, we use the `belongsTo` method:

**Defining The Inverse Of A Relation**

	class Phone extends Eloquent {

		public function user()
		{
			return $this->belongsTo('User');
		}

	}

<a name="one-to-many"></a>
### One To Many

An example of a one-to-many relation is a blog post that "has many" comments. We can model this relation like so:

	class Post extends Eloquent {

		public function comments()
		{
			return $this->hasMany('Comment');
		}

	}

Now we can access the post's comments through the dynamic property:

	$comments = Post::find(1)->comments;

If you need to add further constraints to which posts are retrieved, you may call the `comments` method and continue chaining conditions:

	$comments = Post::find(1)->comments()->where('title', '=', 'foo')->first();

Again, you may override the conventional foreign key by passing a second argument to the `hasMany` method:

	return $this->hasMany('Comment', 'custom_key');

To define the inverse of the relationship on the `Comment` model, we use the `belongsTo` method:

**Defining The Inverse Of A Relation**

	class Comment extends Eloquent {

		public function post()
		{
			return $this->belongsTo('Post');
		}

	}

<a name="many-to-many"></a>
### Many To Many

Many-to-many relations are a more complicated relationship type. An example of such a relationship is a user with many roles, where the roles are also shared by other users. For example, many users may have the role of "Admin". Three database tables are needed for this relationship: `users`, `roles`, and `role_user`. The `role_user` table is derived from the alphabetical order of the related model names, and should have `user_id` and `role_id` columns.

We can define a many-to-many relation using the `belongsToMany` method:

	class User extends Eloquent {

		public function roles()
		{
			return $this->belongsToMany('Role');
		}

	}

Now, we can retrieve the roles through the `User` model:

	$roles = User::find(1)->roles;

If you would like to use an unconventional table name for your pivot table, you may pass it as the second argument to the `belongsToMany` method:

	return $this->belongsToMany('Role', 'user_roles');

You may also override the conventional associated keys:

	return $this->belongsToMany('Role', 'user_roles', 'user_id', 'foo_id');

<a name="polymorphic-relations"></a>
### Polymorphic Relations

Polymorphic relations allow a model to belongs to more than one other model, on a single association. For example, you might have a photo model that belongs to either a staff model or an order model. We would define this relation like so:

	class Photo extends Eloquent {

		public function imageable()
		{
			return $this->morphTo();
		}

	}

	class Staff extends Eloquent {

		public function photos()
		{
			return $this->morphMany('Photo', 'imageable');
		}

	}

	class Order extends Eloquent {

		public function photos()
		{
			return $this->hasMany('Photo', 'imageable');
		}

	}

Now, we can retrieve the photos for either a staff member or an order:

**Retrieving A Polymorphic Relation**

	$staff = Staff::find(1);

	foreach ($staff->photos as $photo)
	{
		//
	}

However, the true "polymorphic" magic is when you access the staff or order from the `Photo` model:

**Retrieving The Owner Of A Polymorphic Relation**

	Photo::find(1);

	$imageable = $photo->imageable;

The `imageable` relation on the `Photo` model will return either a `Staff` or `Order` instance, depending on which type of model owns the photo.

To help understand how this works, let's explore the database structure for a polymorphic relation:

**Polymorphic Relation Table Structure**

	staff
		id - integer
		name - string

	orders
		id - integer
		price - integer

	photos
		id - integer
		path - string
		imageable_id - integer
		imageable_type - string

The key fields to notice here are the `imageable_id` and `imageable_type` on the `photos` table. The ID will contain the ID value of, in this example, the owning staff or order, while the type will contain the class name of the owning model. This is what allows the ORM to determine which type of owning model to return when accessing the `imageable` relation.

<a name="eager-loading"></a>
## Eager Loading

Eager loading exists to alleviate the N + 1 query problem. For example, consider a `Book` model that is related to `Author`. The relationship is defined like so:

	class Book extends Eloquent {

		public function author()
		{
			return $this->belongsTo('Author');
		}

	}

Now, consider the following code:

	foreach (Book::all() as $book)
	{
		echo $book->author->name;
	}

This loop will execute 1 query to retrieve all of the books on the table, then another query for each book to retrieve the author. So, if we have 25 books, this loop would run 26 queries.

Thankfully, we can use eager loading to drastically reduce the number of queries. The relationships that should be eager loaded may be specified via the `with` method:

	foreach (Book::with('author')->get() as $book)
	{
		echo $book->author->name;
	}

In the loop above, only two queries will be executed:

	select * from books

	select * from authors where id in (1, 2, 3, 4, 5, ...)

Wise use of eager loading can drastically increase the performance of your application.

Of course, you may eager load multiple relationships at one time:

	$books = Book::with('author', 'publisher')->get();

You may even eager load nested relationships:

	$books = Book::with('author.contacts')->get();

In the example above, the `author` relationship will be eager loaded, and the author's `contacts` relation will also be loaded.

### Eager Load Constraints

Sometimes you may wish to eager load a relationship, but also specify a condition for the eager load. Here's an example:

	$users = User::with(array('posts' => function($query)
	{
		$query->where('title', 'like', '%first%');

	}))->get();

In this example, we're eager loading the user's posts, but only if the post's title column contains the word "first".

<a name="inserting-related-models"></a>
## Inserting Related Models

You will often need to insert new related models. For example, you may wish to insert a new comment for a post. Instead of manually setting the `post_id` foreign key on the model, you may insert the new comment from its parent `Post` model directly:

**Attaching A Related Model**

	$comment = new Comment(['message' => 'A new comment.']);

	$post = Post::find(1);

	$comment = $post->comments()->save($comment);

In this example, the `post_id` field will automatically be set on the inserted comment.

### Inserting Related Models (Many To Many)

You may also insert related models when working with many-to-many relations. Let's continue using our `User` and `Role` models as examples. We can easily attach new roles to a user using the `attach` method:

**Attaching Many To Many Models**

	$user = User::find(1);

	$user->roles()->attach(1);

You may also pass an array of attributes that should be stored on the pivot table for the relation:

	$user->roles()->attach(1, ['expires' => $expires]);

You may also use the `sync` method to attach related models. The `sync` method accepts an array of IDs to place on the pivot table. After this operation is complete, only the IDs in the array will be on the intermediate table for the model:

**Using Sync To Attach Many To Many Models**

	$user->roles()->sync([1, 2, 3]);

Sometimes you may wish to create a new related model and attach it in a single command. For this operation, you may use the `save` method:

	$role = new Role(['name' => 'Editor']);

	User::find(1)->roles()->save($role);

In this example, the new `Role` model will be saved and attached to the user model. You may also pass an array of attributes to place on the joining table for this operation:

	User::find(1)->roles()->save($role, ['expires' => $expires]);

<a name="working-with-pivot-tables"></a>
## Working With Pivot Tables

As you have already learned, working with many-to-many relations requires the presence of an intermediate table. Eloquent provides some very helpful ways of interacting with this table. For example, let's assume our `User` object has many `Role` objects that it is related to. After accessing this relationship, we may access the `pivot` table on the models:

	$user = User::find(1);

	foreach ($user->roles as $role)
	{
		echo $role->pivot->created_at;
	}

Notice that each `Role` model we retrieve is automatically assigned a `pivot` attribute. This attribute contains a model representing the intermediate table, and may be used as any other Eloquent model.

By default, only the keys will be present on the `pivot` object. If your pivot table contains extra attributes, you must specify them when defining the relationship:

	return $this->belongsToMany('Role')->withPivot('foo', 'bar');

Now the `foo` and `bar` attributes will be accessible on our `pivot` object for the `Role` model.

If your want your pivot table to have automatically maintained `created_at` and `updated_at` timestamps, use the `withTimestamps` method on the relationship definition:

	return $this->belongsToMany('Role')->withTimestamps();

To delete all records on the pivot table for a model, you may use the `delete` method:

**Deleting Records On A Pivot Table**

	User::find(1)->roles()->delete();

Note that this operation does not delete records from the `roles` table, but only from the pivot table.

<a name="collections"></a>
## Collections

All multi-result sets returned by Eloquent either via the `get` method or a relationship return an Eloquent `Collection` object. This objects implements the `IteratorAggregate` PHP interface so it can be iterated over like an array. However, this object also has a variety of other helpful methods for working with result sets.

For example, we may determine if a result set contains a given primary key using the `contains` method:

**Checking If A Collection Contains A Key**

	$roles = User::find(1)->roles;

	if ($roles->contains(2))
	{
		//
	}

Collections may also be converted to an array or JSON:

	$roles = User::find(1)->roles->toArray();

	$roles = User::find(1)->roles->toJson();

If a collection is cast to a string, it will be returned as JSON:

	$roles = (string) User::find(1)->roles;

Sometimes, you may wish to return a custom Collection object with your own added methods. You may specify this on your Eloquent model by overriding the `newCollection` method:

**Returning A Custom Collection Type**

	class User extends Eloquent {

		public function newCollection(array $models = array())
		{
			return new CustomCollection($models);
		}

	}

<a name="accessors-and-mutators"></a>
## Accessors & Mutators

Eloquent provides a convenient way to transform your model attributes when getting or setting them. Simplify define a `getFoo` method on your model to declare an accessor. Keep in mind that the methods should follow camel-casing, even though your database columns are snake-case:

**Defining An Accessor**

	class User extends Eloquent {

		public function getFirstName($value)
		{
			return ucfirst($value);
		}

	}

In the example above, the `first_name` column has an accessor. Note that the value of the attribute is passed to the accessor.

Mutators are declared in a similar fashion:

**Defining A Mutator**

	class User extends Eloquent {

		public function setFirstName($value)
		{
			$this->attributes['first_name'] = strtolower($value);
		}

	}

<a name="mass-assignment"></a>
## Mass Assignment

When creating a new model, you pass an array of attributes to the model constructor. These attributes are then assigned to the model via mass-assignment. This is convenient; however, can be a **serious** security concern when blindly passing user input into a model. If user input is blindly passed into a model, the user is free to modify **any** and **all** of the model's attributes.

A more secure approach to assigning attributes is either to manually assign them, or to set the `fillable` or `guarded` properties on your model.

The `fillable` property specifies which attributes should be mass-assignable. This can be set at the class or instance level.

**Defining Fillable Attributes On A Model**

	class User extends Eloquent {

		protected $fillable = ['first_name', 'last_name', 'email'];

	}

In this example, only the three listed attributes will be mass-assignable.

The inverse of `fillable` is `guarded`, and serves as a "black-list" instead of a "white-list":

**Defining Guarded Attributes On A Model**

	class User extends Eloquent {

		protected $guarded = ['id', 'password'];

	}

In the example above, the `id` and `password` attributes may **not** be mass assigned. All other attributes will be mass assignable. You may also block **all** attributes from mass assignment using the guard method:

**Blocking All Attributes From Mass Assignment**

	protected $guarded = ['*'];

<a name="converting-to-arrays-or-json"></a>
## Converting To Arrays / JSON

When building JSON APIs, you may often need to convert your models and relationships to arrays or JSON. So, Eloquent includes methods for doing so. To convert a model and its loaded relationship to an array, you may use the `toArray` method:

**Converting A Model To An Array**

	$user = User::with('roles')->first();

	return $user->toArray();

Note that entire collections of models may also be converted to arrays:

	return User::all()->toArray();

To convert a model to JSON, you may use the `toJson` method:

**Converting A Model To JSON**

	return User::find(1)->toJson();

Note that when a model or collection is cast to a string, it will be converted to JSON, meaning you can return Eloquent objects directly from your application's routes!

**Returning A Model From A Route**

	Route::get('users', function()
	{
		return User::all();
	});

Sometimes you may wish to limit the attributes that are included in your model's array or JSON form, such as passwords. To do so, add a `hidden` property definition to your model:

**Hiding Attributes From Array Or JSON Conversion**

	class User extends Eloquent {

		protected $hidden = ['password'];

	}

---

## File: errors.md

# Errors & Logging

- [Error Detail](#error-detail)
- [Handling Errors](#handling-errors)
- [Handling 404 Errors](#handling-404-errors)
- [Logging](#logging)

## Error Detail

By default, error detail is enabled for your application. This means that when an error occurs you will be showed an error page with a detailed stack trace and error message. You may turn off error details by setting the `debug` option in your `app/config/app.php` file to `false`. **It is strongly recommend you turn off error detail in a production environment.**

## Handling Errors

By default, the `app/start/global.php` file contains an error handler for all exceptions:

	App::error(function(Exception $exception)
	{
		Log::error($exception);
	});

This is the most basic error handler. However, you may specify more handlers if needed. Handlers are called based on the type-hint of the Exception they handle. For example, you may create a handler that only handles `RuntimeException` instances:

	App::error(function(RuntimeException $exception)
	{
		// Handle the exception...
	});

If an exception handler returns a response, that response will be sent to the browser and no other error handlers will be called:

	App::error(function(InvalidUserException $exception)
	{
		Log::error($exception);

		return 'Sorry! Something is wrong with this account!';
	});

<a name="handling-404-errors"></a>
## Handling 404 Errors

You may register an error handler that handles all "404 Not Found" errors in your application, allowing you to return custom 404 error pages:

	App::missing(function($exception)
	{
		return View::make('errors.missing');
	});

<a name="logging"></a>
## Logging

The Laravel logging facilities provide a simple layer on top of the powerful [Monolog](http://github.com/seldaek/monolog). By default, Laravel is configured to create daily log files for your application, and these files are stored in `app/storage/logs`. You may write information to these logs like so:

	Log::info('This is some useful information.');

	Log::warning('Something could be going wrong.');

	Log::error('Something is really going wrong.');

The logger provides the seven logging levels defined in [RFC 5424](http://tools.ietf.org/html/rfc5424): **debug**, **info**, **notice**, **warning**, **error**, **critical**, and **alert**.

Monolog has a variety of additional handlers you may use for logging. If needed, you may access the underlying Monolog instance being used by Laravel:

	$monolog = Log::getMonolog();

---

## File: events.md

# Events

- [Basic Usage](#basic-usage)
- [Using Classes As Listeners](#using-classes-as-listeners)
- [Event Subscribers](#event-subscribers)

<a name="basic-usage"></a>
## Basic Usage

The Laravel `Event` class provides a simple observer implementation, allowing you to subscribe and listen for events in your application. The Laravel event facilities extend the `Symfony\Component\EventDispatcher\EventDispatcher` class.

**Subscribing To An Event**

	Event::listen('user.login', function($event)
	{
		$event->user->last_login = new DateTime;

		$event->user->save();
	});

**Firing An Event**

	$event = Event::fire('user.login', ['user' => $user]);

Note that the `Event::fire` method returns an `Event` object, allowing you to inspect the event payload after the listeners have been called.

You may also specify a priority when subscribing to events. Listeners with higher priority will be run first, while listeners that have the same priority will be run in order of subscription.

**Subscribing To Events With Priority**

	Event::listen('user.login', 'LoginHandler', 10);

	Event::listen('user.login', 'OtherHandler', 5);

Sometimes, you may wish to stop the propagation of an event to other listeners. You may do so using the `$event->stop()` method.

**Stopping The Propagation Of An Event**

	Event::listen('user.login', function($event)
	{
		// Handle the event...

		$event->stop();
	});

<a name="using-classes-as-listeners"></a>
## Using Classes As Listeners

In some case, you may wish to use a class to handle an event rather than a Closure. Class event listeners will be resolved out of the [Laravel IoC container](/docs/ioc), providing you the full power of dependency injection on your listeners.

**Registering A Class Listener**

	Event::listen('user.login', 'LoginHandler');

By default, the `handle` method on the `LoginHandler` class will be called:

**Defining An Event Listener Class**

	class LoginHandler {

		public function handle($event)
		{
			//
		}

	}

If you do not wish to use the default `handle` method, you may specify the method that should be subscribed:

**Specifying Which Method To Subscribe**

	Event::listen('user.login', 'LoginHandler@onLogin');

<a name="event-subscribers"></a>
## Event Subscribers

Event subscribers are classes that may subscribe to multiple events from within the class itself. Subscribers should extend the `EventSubscriber` class and define a `subscribes` method.

**Defining An Event Subscriber**

	class UserEventHandler extends EventSubscriber {

		/**
		 * Handle user login events.
		 */
		public function onUserLogin($event)
		{
			//
		}

		/**
		 * Handle user logout events.
		 */
		public function onUserLogout($event)
		{
			//
		}

		/**
		 * Register the listeners for the subscriber.
		 *
		 * @return array
		 */
		public static function subscribes()
		{
			return [
				'user.login' => [
					['onUserLogin', 10],
				],
				'user.logout' => [
					['onUserLogout', 10],
				],
			];
		}

	}

Once the subscriber has been defined, it may be registered with the `Event` class.

**Registering An Event Subscriber**

	Event::subscribe(new UserEventHandler);

**Removing An Event Subscriber**

	Event::unsubscribe($subscriber);

---

## File: installation.md

# Installation

- [Install Composer](#install-composer)
- [Install Laravel](#install-laravel)
- [Server Requirements](#server-requirements)
- [Configuration](#configuration)
- [Pretty URLs](#pretty-urls)

<a name="install-composer"></a>
## Install Composer

Laravel utilizes [Composer](http://getcomposer.org) to manage its dependencies. First, download a copy of the `composer.phar`. Once you have the PHAR archive, you can either keep it in your local project directory or move to `usr/local/bin` to use it globally on your system. On Windows, you can use the Composer [Windows installer](https://getcomposer.org/Composer-Setup.exe).

<a name="install-laravel"></a>
## Install Laravel

Once Composer is installed, download the [latest version](https://github.com/laravel/laravel/archive/develop.zip) of the Laravel framework and extract its contents into a directory on your server. Next, in the root of your Laravel application, run the `php composer.phar install` command to install all of the framework's dependencies.

<a name="server-requirements"></a>
## Server Requirements

The Laravel framework has a few system requirements:

- PHP 5.3+
- MCrypt PHP Extension

<a name="configuration"></a>
## Configuration

Laravel needs almost no configuration out of the box. You are free to get started developing! However, you may wish to review the `app/config/app.php` file and its documentation. It contains several options such as `timezone` and `locale` that you may wish to change according to your application.

> **Note:** One configuration option you should be sure to set is the `key` option within `app/config/app.php`. This value should be set to a 32 character, random string. This key is used when encrypting values, and encrypted values will not be safe until it is properly set.

<a name="pretty-urls"></a>
## Pretty URLs

The framework ships with a `public/.htaccess` file that is used to allow URLs without `index.php`. If you use Apache to serve your Laravel application, be sure to enable the `mod_rewrite` module.

If the `.htaccess` file that ships with Laravel does not work with your Apache installation, try this one:

	Options +FollowSymLinks
	RewriteEngine on

	RewriteCond %{REQUEST_FILENAME} !-f
	RewriteCond %{REQUEST_FILENAME} !-d

	RewriteRule . index.php [L]

---

## File: introduction.md

# Introduction

- [Laravel Philosophy](#laravel-philosophy)
- [Learning Laravel](#learning-laravel)

<a name="laravel-philosophy"></a>
## Laravel Philosophy

Laravel is a web application framework with expressive, elegant syntax. We believe development should be an enjoyable, creative experience to be truly fulfilling. Laravel attempts to take the pain out of development by implementing common tasks used in the majority of web projects, such as authentication, routing, sessions, and caching.

Laravel aims to make the development process a pleasing one for the developer without sacrificing application functionality. Happy developers make the best code.

<a name="learning-laravel"></a>
## Learning Laravel

One of the best ways to learn Laravel is to read through the entirety of its documentation. This guide details all aspects of the framework and how to apply them to your application.

In addition to this guide, you may wish to check out some of the Laravel books that are available on the [books page](http://laravel.com/books). These books serve as a good supplemental resource for learning the framework.

---

## File: ioc.md

# IoC Container

- [Introduction](#introduction)
- [Basic Usage](#basic-usage)
- [Automatic Resolution](#automatic-resolution)
- [Practical Usage](#practical-usage)
- [Service Providers](#service-providers)

<a name="introduction"></a>
## Introduction

The Laravel inversion of control container is a powerful tool for managing class dependencies. Dependency injection is a method of remove hard-coded class dependencies. Instead, the dependencies are injected at run-time, allowing for greater flexibility as dependency implementations may be swapped easily.

Understanding the Laravel IoC container is essential to building a powerful, large application, as well as for contributing to the Laravel core itself.

<a name="basic-usage"></a>
## Basic Usage

There are two ways the IoC container can resolve dependencies: via Closure callbacks or automatic resolution. First, we'll explore Closure callbacks. First, a "type" may be bound into the container:

**Binding A Type Into The Container**

	App::bind('foo', function()
	{
		return new FooBar;
	});

**Resolving A Type From The Container**

	$value = App::make('foo');

When the `App::make` method is called, the Closure callback is executed and the result is returned.

Sometimes, you may wish to bind something into the container that should only be resolved once, and the same instance should be returned on subsequent calls into the container:

**Binding A "Shared" Type Into The Container**

	App::singleton('foo', function()
	{
		return new FooBar;
	});

You may also bind an existing object instance into the container using the `instance` method:

**Binding An Existing Instance Into The Container**

	$foo = new Foo;

	App::instance('foo', $foo);

<a name="automatic-resolution"></a>
## Automatic Resolution

The IoC container is powerful enough to resolve classes without any configuration at all in many scenarios. For example:

**Resolving A Class**

	class FooBar {

		public function __construct(Baz $baz)
		{
			$this->baz = $baz;
		}

	}

	$fooBar = App::make('FooBar');

Note that even though we did not register the FooBar class in the container, the container will still be able to resolve the class, even injecting the `Baz` dependency automatically!

When a type is not bound in the container, it will use PHP's Reflection facilities to inspect the class and read the constructor's type-hints. Using this information, the container can automatically build an instance of the class.

However, in some cases, a class may depend on an interface implementation, not a "concrete type". When this is the case, the `App::bind` method must be used to inform the container which interface implementation to inject:

**Binding An Interface To An Implementation**

	App::bind('UserRepositoryInterface', 'DbUserRepository');

Now consider the following controller:

	class UserController extends BaseController {

		public function __construct(UserRepositoryInterface $users)
		{
			$this->users = $users;
		}

	}

Since we have bound the `UserRepositoryInterface` to a concrete type, the `DbUserRepository` will automatically be injected into this controller when it is created.

<a name="practical-usage"></a>
## Practical Usage

Laravel provides several opportunities to use the IoC container to increase the flexibility and testability of your application. One primary example is when resolving controllers. All controllers are resolved through the IoC container, meaning you can type-hint dependencies in a controller constructor, and they will automatically be injected.

**Type-Hinting Controller Dependencies**

	class OrderController extends BaseController {

		public function __construct(OrderRepository $orders)
		{
			$this->orders = $orders;
		}

		public function getIndex()
		{
			$all = $this->orders->all();

			return View::make('orders', compact('all'));
		}

	}

In this example, the `OrderRepository` class will automatically be injected into the controller. This means that when [unit testing](/docs/testing) a "mock" `OrderRepository` may be bound into the container and injected into the controller, allowing for painless stubbing of database layer interaction.

[Filters](/docs/routing#route-filters), [composers](/docs/responses#view-composers), and [event handlers](/docs/events#using-classes-as-listeners) may also be resolved out of the IoC container. When registering them, simply give the name of the class that should be used:

**Other Examples Of IoC Usage**

	Route::filter('foo', 'FooFilter');

	View::composer('foo', 'FooComposer');

	Event::listen('foo', 'FooHandler');

<a name="service-providers"></a>
## Service Providers

Service providers are a great way to group related IoC registrations in a single location. In fact, most of the core Laravel components include service providers. All of the registered service providers for your application are listed in the `providers` array of the `app/config/app.php` configuration file.

To create a service provider, simply extend the `Illuminate\Support\ServiceProvider` class and define a `register` method:

**Defining A Service Provider**

	use Illuminate\Support\ServiceProvider;

	class FooServiceProvider extends ServiceProvider {

		public function register()
		{
			$this->app->bind('foo', function()
			{
				return new Foo;
			})
		}

	}

Note that in the `register` method, the application IoC container is available to you via the `$this->app` property. Once you have created a provider and are ready to register it with your application, simply add it to the `providers` array in your `app` configuration file.

---

## File: lifecycle.md

# Request Lifecycle

- [Overview](#overview)
- [Start Files](#start-files)
- [Application Events](#application-events)

<a name="overview"></a>
## Overview

The Laravel request lifecycle is fairly simple. A request enters your application and is dispatched to the appropriate route or controller. The response from that route is then sent back to the browser and displayed on the screen. Sometimes you may wish to do some processing before or after your routes are actually called. There are several opportunities to do this, two of which are "start" files and application events.

<a name="start-files"></a>
## Start Files

Your application's start files are stored at `app/start`. By default, three are included with your application: `global.php`, `local.php`, and `artisan.php`. For more information about `artisan.php`, refer to the documentation on the [Artisan command line](/docs/commands#registering-commands).

The `global.php` start file contains a few basic items by default, such as the registration of the [Logger](/docs/errors) and the inclusion of your `app/filters.php` file. However, you are free to add anything to this file that you wish. It will be automatically included on _every_ request to your application, regardless of environment. The `local.php` file, on the other hand, is only called when the application is executing in the `local` environment. For more information on environments, check out the [configuration](/docs/configuration) documentation.

Of course, if you have other environments in addition to `local`, you may create start files for those environments as well. They will be automatically included when your application is running in that environment.

<a name="application-events"></a>
## Application Events

You may also do pre and post request processing by registering `before` and `after` application events:

**Registering Application Events**

	App::before(function()
	{
		//
	});

	App::after(function()
	{
		//
	});

Listeners to these events will be run `before` and `after` each request to your application.

---

## File: localization.md

# Localization

- [Introduction](#introduction)
- [Language Files](#language-files)
- [Basic Usage](#basic-usage)
- [Pluralization](#pluralization)

<a name="introduction"></a>
## Introduction

The Laravel `Lang` class provides a convenient way to retrieving strings in various languages, allowing you to easily support multiple languages within your application.

<a name="language-files"></a>
## Language Files

Language strings are stored in files within the `app/lang` directory. Within this directory this should be a directory for each language supported by the application.

	/app
		/lang
			/en
				messages.php
			/es
				messages.php

Language files simply return an array of keyed strings. For example:

**Example Language File**

	<?php

	return array(
		'welcome' => 'Welcome to our application'
	);

The default language for your application is stored in the `app/config/app.php` configuration file. You may change the active language at any time using the `App::locale` method:

**Changing The Default Language At Runtime**

	App::locale('es');

<a name="basic-usage"></a>
## Basic Usage

**Retrieving Lines From A Language File**

	echo Lang::get('messages.welcome');

The first segment of the string passed to the `get` method is the name of the language file, and the second is the name of the line that should be retrieved.

> **Note*: If a language line does not exist, the key will be returned by the `get` method.

**Making Replacements In Lines**

You may also define place-holders in your language lines:

	'welcome' => 'Welcome, :name',

Then, pass a second argument of replacements to the `Lang::get` method:

	echo Lang::get('messages.welcome', ['name' => 'Dayle']);

**Determine If A Language File Contains A Line**

	if (Lang::has('messages.welcome'))
	{
		//
	}

<a name="pluralization"></a>
## Pluralization

Pluralization is a complex problem, as different languages have a variety of complex rules for pluralization. You may easily manage this in your language files. By using a "pipe" character, you may separate the singular and plural forms of a string:

	'apples' => 'There is one apple|There are many apples',

You may then use the `Lang::choice` method to retrieve the line:

	echo Lang::choice('messages.apples', 10);

Since the Laravel translator is powered by the Symfony Translation component, you may also create more explicit pluralization rules easily:

	'apples' => '{0} There are none|[1,19] There are some|[20,Inf] There are many',

---

## File: mail.md

# Mail

- [Configuration](#configuration)
- [Basic Usage](#basic-usage)
- [Embedding Inline Attachments](#embedding-inline-attachments)

<a name="configuration"></a>
## Configuration

Laravel provides a clean, simple API over the popular [SwiftMailer](http://swiftmailer.org) library. The mail configuration file is `app/config/mail.php`, and contains options allowing you to change your SMTP host, port, and credentials, as well as set a global `from` address for all messages delivered by the library. You may use any SMTP server you wish.

<a name="basic-usage"></a>
## Basic Usage

The `Mail::send` method may be used to send an e-mail message:

	Mail::send('emails.welcome', $data, function($m)
	{
		$m->to('foo@example.com', 'John Smith')->subject('Welcome!');
	});

The first argument passed to the `send` method is the name of the view that should be used as the e-mail body. The second is the `$data` that should be passed to the view, and the third is a Closure allowing you to specify various options on the e-mail message.

> **Note:** A `$message` variable is always passed to e-mail views, and allows the inline embedding of attachments. So, it is best to avoid passing a `message` variable in your view payload.

You may also specify a plain text view to use in addition to an HTML view:

	Mail::send(['html.view', 'text.view'], $data, $callback);

You may specify other options on the e-mail message such as any carbon copies or attachments as well:

	Mail::send('emails.welcome', $data, function($m)
	{
		$m->from('us@example.com', 'Laravel');

		$m->to('foo@example.com')->cc('bar@example.com');

		$m->attach($pathToFile);
	});

When attaching files to a message, you may also specify a MIME type and / or a display name:

	$m->attach($pathToFile, ['as' => $display, 'mime' => $mime]);

> **Note:** The message instance passed to a `Mail::send` Closure extends the SwiftMailer message class, allowing you to call any method on that class to build your e-mail messages.

<a name="embedding-inline-attachments"></a>
## Embedding Inline Attachments

Embedding inline images into your e-mails is typically cumbersome; however, Laravel provides a convenient way to attach images to your e-mails and retrieving the appropriate CID.

**Embedding An Image In An E-Mail View**

	
		Here is an image:

		embed($pathToFile); ?>">
	

**Embedding Raw Data In An E-Mail View**

	
		Here is an image from raw data:

		embedData($data, $name); ?>">
	

Note that the `$message` variable is always passed to e-mail views by the `Mail` class.

---

## File: migrations.md

## Migrations & Seeding

- [Introduction](#introduction)
- [Creating Migrations](#creating-migrations)
- [Running Migrations](#running-migrations)
- [Rolling Back Migrations](#rolling-back-migrations)
- [Database Seeding](#database-seeding)

<a name="introduction"></a>
## Introduction

Migrations are a type of version control for your database. They allow a team to modify the database schema and stay up to date on the current schema state. Migrations are typically paired with the [Schema Builder](/docs/schema) to easily manage your application's scheme.

<a name="creating-migrations"></a>
## Creating Migrations

To create a migration, you may use the `migrate:make` command on the Artisan CLI:

**Creating A Migration**

	php artisan migrate:make create_users_table

The migration will be placed in your `app/database/migrations` folder, and will contain a timestamp which allows the framework to determine the order of the migrations.

You may also specify a `--path` option when creating the migration. The path should be relative to the root directory of your installation:

	php artisan migrate:make foo --path=app/migrations

The `--table` and `--create` options may also be used to indicate the name of the table, and whether the migration will be creating a new table:

	php artisan migrate:make create_users_table --table=users --create

<a name="running-migrations"></a>
## Running Migrations

**Running All Outstanding Migrations**

	php artisan migrate

**Running All Outstanding Migrations For A Path**

	php artisan migrate --path=app/foo/migrations

**Running All Outstanding Migrations For A Package**

	php artisan migrate --package=vendor/package

<a name="rolling-back-migrations"></a>
## Rolling Back Migrations

**Rollback The Last Migration Operation**

	php artisan migrate:rollback

**Rollback all migrations**

	php artisan migrate:reset

**Rollback all migrations and run them all again**

	php artisan migrate:refresh

	php artisan migrate:refresh --seed

<a name="database-seeding"></a>
## Database Seeding

Laravel also includes a simple way to seed your database with test data using seed files. All seed files are stored in `app/database/seeds`. Seed files should be named according to the table they seed, and simply return an array of records.

**Example Database Seed File**

	<?php

	return [

		['email' => 'john@foo.com', 'votes' => 10],

		['email' => 'smith@foo.com', 'votes' => 20],

	];

To seed your database, you may use the `db:seed` command on the Artisan CLI:

	php artisan db:seed

You may also seed your database using the `migrate:refresh` command, which will also rollback and re-run all of your migrations:

	php artisan migrate:refresh --seed

---

## File: packages.md

# Package Development

- [Introduction](#introduction)
- [Creating A Package](#creating-a-package)
- [Package Structure](#package-structure)
- [Service Providers](#service-providers)
- [Package Conventions](#package-conventions)
- [Development Workflow](#development-workflow)
- [Package Routing](#package-routing)
- [Package Configuration](#package-configuration)
- [Package Migrations](#package-migrations)
- [Package Assets](#package-assets)
- [Publishing Packages](#publishing-packages)

<a name="introduction"></a>
## Introduction

Packages are the primary way of adding functionality to Laravel. Packages might be anything from a great way to work with dates like [Carbon](https://github.com/briannesbitt/Carbon), or an entire BDD testing framework like [Behat](https://github.com/Behat/Behat).

Of course, there are different types of packages. Some packages are stand-alone, meaning they work with any framework, not just Laravel. Both Carbon and Behat are examples of stand-alone packages. Any of these packages may be used with Laravel by simply requesting them in your `composer.json` file.

On the other hand, other packages are specifically intended for use with Laravel. In previous versions of Laravel, these types of packages were called "bundles". These packages may have routes, controllers, views, configuration, and migrations specifically intended to enhance a Laravel application. As no special process is needed to develop stand-alone packages, this guide primarily covers the development of those that are Laravel specific.

All Laravel packages are distributed via [Packagist](http://packagist.org) and [Composer](http://getcomposer.org), so learning about these wonderful PHP package distribution tools is essential.

<a name="creating-a-package"></a>
## Creating A Package

The easiest way to create a new package for use with Laravel is the `workbench` Artisan command.

**Issuing The Workbench Artisan Command**

	php artisan workbench

This command will prompt you for several pieces of information, such as the vendor and name of the package, as well as your name and e-mail address. These pieces of information are used to create the namespace and `composer.json` of your package.

The vendor name is a way to distinguish your package from other packages of the same name from different authors. For example, if I (Taylor Otwell) were to create a new package named "Zapper", the vendor name could be `Taylor` while the package name would be `Zapper`.

Once the `workbench` command has been executed, your package will be available within the `workbench` directory of your Laravel installation. First, you should run a `composer install` command from the root directory of your workbench package, which will install any dependencies and generate the Composer autoload files for your package. You may instruct the `workbench` command to do this automatically when creating a package using the `--composer` directive:

**Creating A Workbench Package And Running Composer**

	php artisan workbench --composer

Next, you should register the `ServiceProvider` that was created for your package. You may register the provider by adding it to the `providers` array in the `app/config/app.php` file. This will instruct Laravel to load your package when your application starts. Service providers use a `[Package]ServiceProvider` naming convention. So, using the example above, you would add `Taylor\Zapper\ZapperServiceProvider` to the `providers` array.

Once the provider has been registered, you are ready to start developing your package! However, before diving in, you may wish to review the sections below to get more familiar with the package structure and development workflow.

<a name="package-structure"></a>
## Package Structure

When using the `workbench` command, your package will be setup with conventions that allow the package to integrate well with other parts of the Laravel framework:

**Basic Package Directory Structure**

	/src
		/Vendor
			/Package
				PackageServiceProvider.php
		/config
		/lang
		/migrations
		/views
	/tests
	/public

Let's explore this structure further. The `src/Vendor/Package` directory is the home of all of your package's classes, including the `ServiceProvider`. The `config`, `lang`, `migrations`, and `views` directories, as you might guess, contain the corresponding resource for your package. Packages may have any of these resources, just like "regular" applications.

<a name="service-providers"></a>
## Service Providers

Service providers are simply bootstrap classes for packages. By default, they contain two methods: `boot` and `register`. Within these methods you may do anything you like: include a routes file, register bindings in the IoC container, attach to events, or anything else you wish to do.

The `register` method is called immediately when the service provider is registered, while the `boot` command is only called right before a request is routed. So, if actions in your service provider rely on another service provider already being registered, or you are overriding services bound by another provider, you should use the `boot` method.

When creating a package using the `workbench`, the `boot` command will already contain one action:

	$this->package('vendor/package');

This method allows Laravel to know how to properly load the views, configuration, and other resources for your application. In general, there should be no need for you to change this line of code, as it will setup the package using the workbench conventions.

<a name="package-conventions"></a>
## Package Conventions

When utilizing resources from a package, such as configuration items or views, a double-colon syntax will generally be used:

**Loading A View From A Package**

	return View::make('package::view.name');

**Retrieving A Package Configuration Item**

	return Config::get('package::group.option');

> **Note:** If your package contains migrations, consider prefixing the migration name with your package name to avoid potential class name conflicts with other packages.

<a name="development-workflow"></a>
## Development Workflow

When developing a package, it is useful to be able to develop within the context of an application, allowing you to easily view and experiment with your templates, etc. So, to get started, install a fresh copy of the Laravel framework, then use the `workbench` command to create your package structure.

After the `workbench` command has created your package. You may `git init` from the `workbench/[vendor]/[package]` directory and `git push` your package straight from the workbench! This will allow you to conveniently develop the package in an application context without being bogged down by constant `composer update` commands.

Since your packages are in the `workbench` directory, you may be wondering how Composer knows to autoload your package's files. When the `workbench` directory exists, Laravel will intelligently scan it for packages, loading their Composer autoload files when the application starts!

<a name="package-routing"></a>
## Package Routing

In prior versions of Laravel, a `handles` clause was used to specify which URIs a package could respond to. However, in Laravel 4, a package may respond to any URI. To load a routes file for your package, simply `include` it from within your service provider's `register` method.

**Including A Routes File From A Service Provider**

	public function register()
	{
		$this->package('vendor/package');

		include __DIR__.'/routes.php';
	}

<a name="package-configuration"></a>
## Package Configuration

Some packages may require configuration files. These files should be defined in the same way as typical application configuration files. And, when using the default `$this->package` method of registering resources in your service provider, may be accessed using the usual "double-colon" syntax:

**Accessing Package Configuration Files**

	Config::get('package::file.option');

However, if your package contains a single configuration file, you may simply name the file `config.php`. When this is done, you may access the options directly, without specifying the file name:

**Accessing Single File Package Configuration**

	Config::get('package::option');

### Cascading Configuration Files

When other developers install your package, they may wish to override some of the configuration options. However, if they change the values in your package source code, they will be overwritten the next time Composer updates the package. Instead, the `config:publish` artisan command should be used:

**Executing The Config Publish Command**

	php artisan config:publish --package="vendor/package"

When this command is executed, the configuration files for your application will be copied to `app/config/packages/vendor/package` where they can be safely modified by the developer!

> **Note:** The developer may also create environment specific configuration files for your package by placing them in `app/config/packages/vendor/package/environment`.

<a name="package-migrations"></a>
## Package Migrations

You may easily create and run migrations for any of your packages. To create a migration for a package in the workbench, use the `--bench` option:

**Creating Migrations For Workbench Packages**

	php artisan migrate:make create_users_table --bench="vendor/package"

**Running Migrations For Workbench Packages**

	php artisan migrate --bench="vendor/package"

To run migrations for a finished package that was installed via Composer into the `vendor` directory, you may use the `--package` directive:

**Running Migrations For An Installed Package**

	php artisan migrate --package="vendor/package"

<a name="package-assets"></a>
## Package Assets

Some packages may have assets such as JavaScript, CSS, and images. However, we are unable to link to assets in the `vendor` or `workbench` directories, so we need a way to move these assets into the `public` directory of our application. The `asset:publish` command will take care of this for you:

**Moving Package Assets To Public**

	php artisan asset:publish package/vendor

If the package is still in the `workbench`, use the `--bench` directive:

	php artisan asset:publish --bench="package/vendor"

This command will move the assets into the `public/packages` directory according to the vendor and package name. So, a package named `userscape/kudos` would have its assets moved to `public/packages/userscape/kudos`. Using this asset publishing convention allows you to safely code asset path in your package's views.

<a name="publishing-packages"></a>
## Publishing Packages

When your package is ready to publish, you should submit the package to the [Packagist](http://packagist.org) repository. If the package is specific to Laravel, consider adding a `laravel` tag to your package's `composer.json` file.

Also, it is courteous and helpful to tag your releases so that developers can depend on stable versions when requesting your package in their `composer.json` files. If a stable version is not ready, consider using the `branch-alias` Composer directive.

Once your package has been published, feel free to continue developing it within the application context created by `workbench`. This is a great way to continue to conveniently develop the package even after it has been published.

Some organizations choose to host their own private repository of packages for their own developers. If you are interested in doing this, review the documentation for the [Satis](http://github.com/composer/satis) project provided by the Composer team.

---

## File: pagination.md

# Pagination

- [Configuration](#configuration)
- [Usage](#usage)

<a name="configuration"></a>
## Configuration

In other frameworks, pagination can be very painful. Laravel makes it a breeze. There is a single configuration option in the `app/config/view.php` file. The `pagination` option specifies which view should be used to create pagination links. By default, Laravel includes two views.

The `pagination::slider` view will show an intelligent "range" of links based on the current page, while the `pagination::simple` view will simply show "previous" and "next" buttons. **Both views are compatible with Twitter Bootstrap out of the box.**

<a name="usage"></a>
## Usage

There are several ways to paginate items. The simplest is by using the `paginate` method on the query builder or an Eloquent model.

**Paginating Database Results**

	$users = DB::table('users')->paginate(15);

You may also paginate [Eloquent](/docs/eloquent) models:

**Paginating An Eloquent Model**

	$users = User::where('votes', '>', 100)->paginate(15);

The argument passed to the `paginate` method is the number of items you wish to display per page. Once you have retrieved the results, you may display them on your view, and create the pagination links using the `links` method:

	
		<?php foreach ($users as $user): ?>
			<?php echo $user->name;
		<?php endforeach; ?>
	

	<?php echo $users->links(); ?>

This is all it takes to create a pagination system! Note that we did not have to inform the framework of the current page. Laravel will determine this for you automatically.

Sometimes you may wish to create a pagination instance manually, passing it an array of items. You may do so using the `Paginator::make` method:

**Creating A Paginator Manually**

	$paginator = Paginator::make($items, $totalItems, $perPage);

---

## File: queries.md

## Query Builder

- [Introduction](#introduction)
- [Selects](#selects)
- [Joins](#joins)
- [Advanced Wheres](#advanced-wheres)
- [Aggregates](#aggregates)
- [Raw Expressions](#raw-expressions)
- [Inserts](#inserts)
- [Updates](#updates)
- [Deletes](#deletes)

<a name="introduction"></a>
## Introduction

The database query builder provides a convenient, fluent interface to creating and running database queries. It can be used to perform most database operations in your application, and works on all supported database systems.

> **Note:** The Laravel query builder uses PDO parameter binding throughout to protect your application against SQL injection attacks. There is no need to clean strings being passed as bindings.

<a name="selects"></a>
## Selects

**Retrieving All Rows From A Table**

	$users = DB::table('users')->get();

	foreach ($users as $user)
	{
		var_dump($user->name);
	}

**Retrieving A Single Row From A Table**

	$user = DB::table('users')->where('name', 'John')->first();

	var_dump($user->name);

**Retrieving A Single Column From A Row**

	$name = DB::table('users')->where('name', 'John')->pluck('name');

**Specifying A Select Clause**

	$users = DB::table('users')->select('name', 'email')->get();

	$users = DB::table('users')->distinct()->get();

	$users = DB::table('users')->select('name as user_name')->get();

**Using Where Operators**

	$users = DB::table('users')->where('votes', '>', 100)->get();

**Or Statements**

	$users = DB::table('users')
	                    ->where('votes', '>', 100)
	                    ->orWhere('name', 'John')
	                    ->get();

**Using Where Between**

	$users = DB::table('users')
	                    ->whereBetween('votes', array(1, 100))->get();

**Order By, Group By, And Having**

	$users = DB::table('users')
	                    ->orderBy('name', 'desc')
	                    ->groupBy('count')
	                    ->having('count', '>', 100)
	                    ->get();

**Offset & Limit**

	$users = DB::table('users')->skip(10)->take(5)->get();

<a name="joins"></a>
## Joins

The query builder may also be used to write join statements. Take a look at the following examples:

**Basic Join Statement**

	DB::table('users')
	            ->join('contacts', 'users.id', '=', 'contacts.user_id')
	            ->join('orders', 'users.id', '=', 'orders.user_id')
	            ->select('users.id', 'contacts.phone', 'orders.price');

You may also specify more advanced join clauses:

	DB::table('users')
	        ->join('contacts', function($join)
	        {
	        	$join->on('users.id', '=', 'contacts.user_id')->orOn(...);
	        })
	        ->get();

<a name="advanced-wheres"></a>
## Advanced Wheres

Sometimes you may need to create more advanced where clauses such as "where exists" or nested parameter groupings. The Laravel query builder can handle these as well:

**Parameter Grouping**

	DB::table('users')
	            ->where('name', '=', 'John')
	            ->orWhere(function($query)
	            {
	            	$query->where('votes', '>', 100)
	            	      ->where('title', '<>', 'Admin');
	            })
	            ->get();

The query above will produce the following SQL:

	select * from users where name = 'John' or (votes > 100 and title <> 'Admin')

**Exists Statements**

	DB::table('users')
	            ->whereExist(function($query)
	            {
	            	$query->select(DB::raw(1))
	            	      ->from('orders')
	            	      ->whereRaw('orders.user_id = users.id');
	            })
	            ->get();

The query above will produce the following SQL:

	select * from users 
	where exists (
		select 1 from orders where orders.user_id = users.id
	)

<a name="aggregates"></a>
## Aggregates

The query builder also provides a variety of aggregate methods, such as `count`, `max`, `min`, `avg`, and `sum`.

**Using Aggregate Methods**

	$users = DB::table('users')->count();

	$price = DB::table('orders')->max('price');

	$price = DB::table('users')->min('price');

	$price = DB::table('users')->avg('price');

	$total = DB::table('users')->sum('votes');

<a name="raw-expressions"></a>
## Raw Expressions

Sometimes you may need to use a raw expression in a query. These expressions will be injected into the query as strings, so be careful not to create any SQL injection points! To create a raw expression, you may use the `DB::raw` method:

**Using A Raw Expression**

	$users = DB::table('users')
	                     ->select(DB:raw('count(*) as user_count, status'))
	                     ->where('status', '<>', 1)
	                     ->groupBy('status')
	                     ->get();

<a name="inserts"></a>
## Inserts

**Inserting Records Into A Table**

	DB::table('users')->insert(
		['email' => 'john@gmail.com', 'votes' => 0],
	);

**Inserting Multiple Records Into A Table**

	DB::table('users')->insert(
		['email' => 'taylor@gmail.com', 'votes' => 0],
		['email' => 'dayle@gmail.com', 'votes' => 0],
	);

<a name="updates"></a>
## Updates

**Updating Records In A Table**

	DB::table('users')
	            ->where('id', 1)
	            ->update(['votes' => 1]);

<a name="deletes"></a>
## Deletes

**Deleting Records In A Table**

	DB::table('users')->where('votes', < 100)->delete();

**Deleting All Records From A Table**

	DB::table('users')->delete();

---

## File: redis.md

# Redis

- [Introduction](#introduction)
- [Configuration](#configuration)
- [Usage](#usage)

<a name="introduction"></a>
## Introduction

[Redis](http://redis.io) is an open source, advanced key-value store. It is often referred to as a data structure server since keys can contain [strings](http://redis.io/topics/data-types#strings), [hashes](http://redis.io/topics/data-types#hashes), [lists](http://redis.io/topics/data-types#lists), [sets](http://redis.io/topics/data-types#sets), and [sorted sets](http://redis.io/topics/data-types#sorted-sets).

<a name="configuration"></a>
## Configuration

The Redis configuration for your application is stored in the **app/config/database.php** file. Within this file, you will see a **redis** array containing the Redis servers used by your application:

	'redis' => array(

		'default' => array('host' => '127.0.0.1', 'port' => 6379),

	),

The default server configuration should suffice for development. However, you are free to modify this array based on your environment. Simply give each Redis server a name, and specify the host and port used by the server.

<a name="usage"></a>
## Usage

You may get a Redis instance by calling the `Redis::connection` method:

	$redis = Redis::connection();

This will give you an instance of the default Redis server. You may pass the server name to the `connection` method to get a specific server as defined in your Redis configuration:

	$redis = Redis::connection('other');

Once you have an instance of the Redis client, we may issue any of the [Redis commands](http://redis.io/commands) to the instance. Laravel uses magic methods to pass the commands to the Redis server:

	$redis->set('name', 'Taylor');

	$name = $redis->get('name');

	$values = $redis->lrange('names', 5, 10);

Notice the arguments to the command are simply passed into the magic method. Of course, you are not required to use the magic methods, you may also pass commands to the server using the `command` method:

	$values = $redis->command('lrange', array(5, 10));

When you are simply executing commands against the default connection, just use static magic methods on the `Redis` class:

	Redis::set('name', 'Taylor');

	$name = Redis::get('name');

	$values = Redis::lrange('names', 5, 10);

> **Note:** Redis [cache](/docs/cache) and [session](/docs/session) drivers are included with Laravel.

---

## File: requests.md

# Requests & Input

- [Basic Input](#basic-input)
- [Cookies](#cookies)
- [Old Input](#old-input)
- [Files](#files)
- [Request Information](#request-information)

<a name="basic-input"></a>
## Basic Input

You may access all user input with a few simple methods. You do not need to worry about the HTTP verb used for the request, as input is accessed in the same way for all verbs.

**Retrieving An Input Value**

	$name = Input::get('name');

**Retrieving A Default Value If The Input Value Is Absent**

	$name = Input::get('name', 'Sally');

**Determining If An Input Value Is Present**

	if (Input::has('name'))
	{
		//
	}

**Getting All Input For The Request**

	$input = Input::all();

**Getting Only Some Of The Request Input**

	$input = Input::only('username', 'password');

	$input = Input::except('credit_card');

Some JavaScript libraries such as Backbone may send input to the application as JSON.

**Retrieving JSON Input**

	$input = Input::json();

<a name="cookies"></a>
## Cookies

All cookies created by the Laravel framework are encrypted and signed with an authentication code, meaning they will be considered invalid if they have been changed by the client.

**Retrieving A Cookie Value**

	$value = Cookie::get('name');

**Attaching A New Cookie To A Response**

	$response = Response::make('Hello World');

	$response->withCookie(Cookie::make('name', 'value', $minutes));

**Creating A Cookie That Lasts Forever**

	$cookie = Cookie::forever('name', 'value');

<a name="old-input"></a>
## Old Input

You may need to keep input from one request until the next request. For example, you may need to re-populate a form after checking it for validation errors.

**Flashing Input To The Session**

	Input::flash();

**Flashing Only Some Input To The Session**

	Input::flashOnly('username', 'email');

	Input::flashExcept('password');

Since you often will want to flash input in association with a redirect to the previous page, you may easily chain input flashing onto a redirect.

	return Redirect::to('form')->withInput();

	return Redirect::to('form')->withInput(Input::except('password'));

> **Note:** You may flash other data across requests using the [Session](/docs/session) class.

**Retrieving Old Data**

	Input::old('username');

<a name="files"></a>
## Files

**Retrieving An Uploaded File**

	$file = Input::file('photo');

**Determining If A File Was Uploaded**

	if (Input::hasFile('photo'))
	{
		//
	}

The object returned by the `file` method is an instance of the `Symfony\Component\HttpFoundation\File\UploadedFile` class, which extends the PHP `SplFileInfo` class and provides a variety of methods for interacting with the file.

**Moving An Uploaded File**

	Input::file('photo')->move($destinationPath);

	Input::file('photo')->move($destinationPath, $fileName);

**Retrieving The Path To An Uploaded File**

	$path = Input::file('photo')->getRealPath();

**Retrieving The Size Of An Uploaded File**

	$size = Input::file('photo')->getSize();

**Retrieving The MIME Type Of An Uploaded File**

	$mime = Input::file('photo')->getMimeType();

<a name="request-information"></a>
## Request Information

The `Request` class provides many methods for examining the HTTP request for your application and extends the `Symfony\Component\HttpFoundation\Request` class. Here are some of the highlights.

**Retrieving The Request URI**

	$uri = Request::path();

**Determining If The Request Path Matches A Pattern**

	if (Request::is('admin/*'))
	{
		//
	}

**Get The Request URL**

	$url = Request::url();

**Retrieving A Request Header**

	$value = Request::header('Content-Type');

**Retrieving Values From $_SERVER**

	$value = Request::server('PATH_INFO');

**Determine If The Request Is Using AJAX**

	if (Request::ajax())
	{
		//
	}

**Determining If The Request Is Over HTTPS**

	if (Request::secure())
	{
		//
	}

---

## File: responses.md

# Views & Responses

- [Basic Responses](#basic-responses)
- [Redirects](#redirects)
- [Views](#views)
- [View Composers](#view-composers)
- [Special Responses](#special-responses)

<a name="basic-responses"></a>
## Basic Responses

**Returning Strings From Routes**

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

**Creating Custom Responses**

A `Response` instance inherits from the `Symfony\Component\HttpFoundation\Response` class, providing a variety of methods for building HTTP responses.

	$response = Response::make($contents, $statusCode);

	$response->headers->set('Content-Type', $value);

	return $response;

**Attaching Cookies To Responses**

	$cookie = Cookie::make('name', 'value');

	return Response::make($content)->withCookie($cookie);

<a name="redirects"></a>
## Redirects

**Returning A Redirect**

	return Redirect::to('user/login');

**Returning A Redirect To A Named Route**

	return Redirect::route('login');

**Returning A Redirect To A Named Route With Parameters**

	return Redirect::route('profile', ['user' => 1]);

**Returning A Redirect To A Controller Action**

	return Redirect::action('HomeController@index');

**Returning A Redirect To A Controller Action With Parameters**

	return Redirect::action('UserController@profile', ['user' => 1]);

<a name="views"></a>
## Views

Views typically contain the HTML of your application and provide a convenient way of separating your controller and domain logic from your presentation logic. Views are stored in the `app/views` directory.

A simple view could look something like this:

	// View stored in app/views/greeting.php

	<html>
		
			<h1>Hello, <?php echo $name; ?></h1>
		
	</html>

This view may be returned to the browser like so:

	Route::get('/', function()
	{
		return View::make('greeting', ['name' => 'Taylor']);
	});

The second argument passed to `View::make` is an array of data that should be made available to the view.

**Passing Data To Views**

	$view = View::make('greeting', $data);

	$view = View::make('greeting')->with('name', 'Steve');

In the example above the variable `$name` would be accessible from the view, and would contain `Steve`.

**Passing A Sub-View To A View**

Sometimes you may wish to pass a view into another view. For example, given a sub-view stored at `app/views/child/view.php`, we could pass it to another view like so:

	$view = View::make('greeting')->nest('child', 'child.view');

	$view = View::make('greeting')->nest('child', 'child.view', $data);

The sub-view can then be rendered from the parent view:

	<html>
		
			<h1>Hello!</h1>
			<?php echo $child; ?>
		
	</html>

<a name="view-composers"></a>
## View Composers

View composers are callbacks or class methods that are called when a view is created. If you have data that you want bound to a given view each time that view is created throughout your application, a view composer can organize that code into a single location. Therefore, view composers may function like "view models" or "presenters".

**Defining A View Composer**

	View::composer('profile', function($event)
	{
		$event->view->with('count', User::count());
	});

Now each time the `profile` view is created, the `count` data will be bound to the view.

If you would rather use a class based composer, which will provide the benefits of being resolved through the application [IoC container](/docs/ioc), you may do so:

	View::composer('profile', 'ProfileComposer');

A view composer class should be defined like so:

	class ProfileComposer {

		public function compose($event)
		{
			$event->view->with('count', User::count());
		}

	}

Note that there is no convention on where composer classes may be stored. You are free to store them anywhere as long as they can be autoloaded using the directives in your `composer.json` file.

<a name="special-responses"></a>
## Special Responses

**Creating A JSON Response**

	return Response::json(['name' => 'Steve', 'state' => 'CA']);

**Creating a File Download Response**

	return Response::download($pathToFile);

	return Response::download($pathToFile, $status, $headers);

---

## File: routing.md

# Routing

- [Basic Routing](#basic-routing)
- [Route Parameters](#route-parameters)
- [Route Filters](#route-filters)
- [Named Routes](#named-routes)
- [Route Groups](#route-groups)
- [Throwing 404 Errors](#throwing-404-errors)

<a name="basic-routing"></a>
## Basic Routing

Most of the routes for your application will be defined in the `app/routes.php` file. The simplest Laravel routes consist of a URI and a Closure callback.

**Basic GET Route**

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

**Basic POST Route**

	Route::post('foo/bar', function()
	{
		return 'Hello World';
	});

**Registering A Route Responding To Any HTTP Verb**

	Route::any('foo', function()
	{
		return 'Hello World';
	});

**Forcing A Route To Be Served Over HTTPS**

	Route::get('foo', ['https', function()
	{
		return 'Must be over HTTPS';
	}]);

<a name="route-parameters"></a>
## Route Parameters

	Route::get('user/{id}', function($id)
	{
		return 'User '.$id;
	});

**Optional Route Parameters**

	Route::get('user/{name?}', function($name)
	{
		return $name;
	});

**Optional Route Parameters With Defaults**

	Route::get('user/{name?}', function($name = 'John')
	{
		return $name;
	});

**Regular Expression Route Constraints**

	Route::get('user/{name}', function($name)
	{
		//
	})
	->where('name', 'A-Za-z');

<a name="route-filters"></a>
## Route Filters

Route filters provide a convenient way of limiting access to a given route, which is useful for creating areas of your site which require authentication. There are several filters included in the Laravel framework, including an `auth` filter, a `guest` filter, and a `csrf`filter. These are located in the `app/filters.php` file.

**Defining A Route Filter**

	Route::filter('old', function()
	{
		if (Input::get('age') < 200)
		{
			return Redirect::to('home');
		}
	}
	});

If a response is returned from a filter, that response will be considered the response to the request and the route will not be executed.

**Attaching A Filter To A Route**

	Route::get('user', ['before' => 'old', function()
	{
		return 'You are over 200 years old!';
	}]);

**Attaching Multiple Filters To A Route**

	Route::get('user', ['before' => 'auth|old', function()
	{
		return 'You are authenticated and over 200 years old!';
	}]);

**Specifying Filter Parameters**

	Route::filter('age', function($value)
	{
		//
	});

	Route::get('user', ['before' => 'age:200', function()
	{
		return 'Hello World';
	}]);

**Pattern Based Filters**

You may also specify that a filter applies to an entire set of routes based on their URI.

	Route::filter('admin', function()
	{
		//
	});

	Route::when('admin/*', 'admin');

In the example above, the `admin` filter would be applied to all routes beginning with `admin/`. The asterisk is used as a wildcard, and will match any combination of characters.

**Filter Classes**

For advanced filtering, you may wish to use a class instead of a Closure. Since filter classes are resolved out of the application [IoC container](/docs/ioc), you will be able to utilize dependency injection in these filters for greater testability.

**Defining A Filter Class**

	class FooFilter {

		public function filter()
		{
			// Filter logic...
		}

	}

**Registering A Class Based Filter**

	Route::filter('foo', 'FooFilter');

<a name="named-routes"></a>
## Named Routes

Named routes make referring to routes when generating redirects or URLs more convenient. You may specify a name for a route like so:

	Route::get('user/profile', ['as' => 'profile', function()
	{
		//
	}]);

Now, you may use the route's name when generating URLs or redirects:

	$url = URL::route('profile');

	$redirect = Redirect::route('profile');

<a name="route-groups"></a>
## Route Groups

Sometimes you may need to apply filters to a group of routes. Instead of specifying the filter on each route, you may use a route group:

	Route::group(['before' => 'auth'], function()
	{
		Route::get('/', function()
		{
			// Has Auth Filter
		});

		Route::get('user/profile', function()
		{
			// Has Auth Filter
		});
	});

<a name="throwing-404-errors"></a>
## Throwing 404 Errors

There are two ways to manually trigger a 404 error from a route. First, you may use the `App::abort` method:

	App::abort(404);

Second, you may throw an instance of `Symfony\Component\HttpKernel\Exception\NotFoundHttpException`.

More information on handling 404 exceptions and using custom responses for these errors may be found in the [errors](/docs/errors#handling-404-errors) section of the documentation.

---

## File: schema.md

## Schema Builder

- [Introduction](#introduction)
- [Creating & Dropping Tables](#creating-and-dropping-tables)
- [Adding Columns](#adding-columns)
- [Dropping Columns](#dropping-columns)
- [Adding Indexes](#adding-indexes)
- [Dropping Indexes](#dropping-indexes)

<a name="introduction"></a>
## Introduction

The Laravel `Schema` class provides a database agnostic way of manipulating tables. It works well with all of the databases supported by Laravel, and has a unified API across all of these systems.

<a name="creating-and-dropping-tables"></a>
## Creating & Dropping Tables

To create a new database table, the `Schema::create` method is used:

	Schema::create('users', function($table)
	{
		$table->increments('id');
	});

The first argument passed to the `create` method is the name of the table, and the second is a `Closure` which will receive a `Blueprint` object which may be used to define the new table.

To specify which connection the schema operation should take place on, use the `Schema::connection` method:

	Schema::connection('foo')->create('users', function($table)
	{
		$table->increments('id'):
	});

To drop a table, you may use the `Schema::drop` method:

	Schema::drop('users');

	Schema::dropIfExists('users');

<a name="adding-columns"></a>
## Adding Columns

To update an existing table, we will use the `Schema::table` method:

	Schema::table('users', function($table)
	{
		$table->string('email');
	});

The table builder contains a variety of column types that you may use when building your tables:

Command  | Description
------------- | -------------
`$table->increments('id');`  |  Incrementing ID to the table (primary key).
`$table->string('email');`  |  VARCHAR equivalent column
`$table->string('name', 100);`  |  VARCHAR equivalent with a length
`$table->integer('votes');`  |  INTEGER equivalent to the table
`$table->float('amount');`  |  FLOAT equivalent to the table
`$table->decimal('amount', 5, 2);`  |  DECIMAL equivalent with a precision and scale
`$table->boolean('confirmed');`  |  BOOLEAN equivalent to the table
`$table->date('created_at');`  |  DATE equivalent to the table
`$table->dateTime('created_at');`  |  DATETIME equivalent to the table
`$table->time('sunrise');`  |  TIME equivalent to the table
`$table->timestamp('added_on');`  |  TIMESTAMP equivalent to the table
`$table->timestamps();`  |  Adds **created\_at** and **updated\_at** columns
`$table->text('description');`  |  TEXT equivalent to the table
`$table->binary('data');`  |  BLOB equivalent to the table
`$table->enum('choices', ['foo', 'bar']);` | ENUM equivalent to the table
`->nullable()`  |  Designate that the column allows NULL values
`->default($value)`  |  Declare a default value for a column
`->unsigned()`  |  Set INTEGER to UNSIGNED

<a name="dropping-columns"></a>
## Dropping Columns

**Dropping A Column From A Database Table**

	Schema::table('users', function($table)
	{
		$table->dropColumn('votes');
	});

<a name="adding-indexes"></a>
## Adding Indexes

The schema builder supports several types of indexes. There are two ways to add them. First, you may fluently define them on a column definition, or you may add them separately:

**Fluently Creating A Column And Index**

	$table->string('email')->unique();

Or, you may choose to add the indexes on separate lines. Below is a list of all available index types:

Command  | Description
------------- | -------------
`$table->primary('id');`  |  Adding a primary key
`$table->primary(array('first', 'last'));`  |  Adding composite keys
`$table->unique('email');`  |  Adding a unique index
`$table->index('state');`  |  Adding a basic index

<a name="dropping-indexes"></a>
## Dropping Indexes

To drop index you must specify the index's name. Laravel assigns a reasonable name to the indexes by default. Simply concatenate the table name, the names of the column in the index, and the index type. Here are some examples:

Command  | Description
------------- | -------------
`$table->dropPrimary('users_id_primary');`  |  Dropping a primary key from the "users" table
`$table->dropUnique('users_email_unique');`  |  Dropping a unique index from the "users" table
`$table->dropIndex('geo_state_index');`  |  Dropping a basic index from the "geo" table

---

## File: security.md

# Security

- [Configuration](#configuration)
- [Storing Passwords](#storing-passwords)
- [Authenticating Users](#authenticating-users)
- [Protecting Routes](#protecting-routes)
- [Encryption](#encryption)

<a name="configuration"></a>
## Configuration

Laravel aims to make implementing authentication very simple. In fact, almost everything is configured for you out of the box. The authentication configuration file is located at `app/config/auth.php`, which contains several well documented options for tweaking the behavior of the authentication facilities.

By default, Laravel includes a `User` model in your `app/models` directory which may be used with the default Eloquent authentication driver. If your application is not using Eloquent, you may use the `database` authentication driver which uses the Laravel query builder.

<a name="storing-passwords"></a>
## Storing Passwords

The Laravel `Hash` class provides secure Bcrypt hashing:

**Hashing A Password Using Bcrypt**

	$password = Hash::make('secret');

**Verifying A Password Against A Hash**

	if (Hash::check('secret', $hashedPassword))
	{
		// The passwords match...
	}

<a name="authenticating-users"></a>
## Authenticating Users

To log a user into your application, you may use the `Auth::attempt` method.

	if (Auth::attempt(['email' => $email, 'password' => $password]))
	{
		// The user's credentials are valid...
	}

Take note that `email` is not a required option, it is merely used for example. You should use whatever column name corresponds to a "username" in your database.

If you would like to provide "remember me" functionality in your application, you may pass `true` as the second argument to the `attempt` method, which will keep the user authenticated indefinitely (or until they manually logout):

**Authenticating A User And "Remembering" Them**

	if (Auth::attempt(['email' => $email, 'password' => $password], true))
	{
		// The user is being remembered...
	}	

**Note:** If the `attempt` method returns `true`, the user is considered logged into the application.

Once a user is authenticated, you may access the User model / record:

**Accessing The Logged In User**

	$email = Auth::user()->email;

**Logging A User Out Of The Application**

	Auth::logout();

<a name="protecting-routes"></a>
## Protecting Routes

Route filters may be used to allow only authenticated users to access a given route. Laravel provides the `auth` filter by default, and it is defined in `app/filters.php`.

**Protecting A Route**

	Route::get('profile', ['before' => 'auth', function()
	{
		// Only authenticated users may enter...
	}]);

<a name="encryption"></a>
## Encryption

Laravel provides facilities for strong AES-256 encryption via the mcrypt PHP extension:

**Encrypting A Value**

	$encrypted = Crypt::encrypt('secret');

> **Note:** Be sure to set a 32 character, random string in the `key` option of the `app/config/app.php` file. Otherwise, encrypted values will not be secure.

**Decrypting A Value**

	$decrypted = Crypt::decrypt($encryptedValue);

---

## File: session.md

# Session

- [Configuration](#configuration)
- [Session Usage](#session-usage)
- [Flash Data](#flash-data)
- [Database Sessions](#database-sessions)

<a name="configuration"></a>
## Configuration

Since HTTP driven applications are stateless, sessions provide a way to store information about the user across requests. Laravel ships with a variety of session back-ends available for use through a clean, unified API. Support for popular back-ends such as [Memcached](http://memcached.org), [Redis](http://redis.io), and databases is included out of the box.

The session configuration is stored in `app/config/session.php`. Be sure to review the well documented options available to you in this file. By default, Laravel is configured to use the `cookie` session driver, which will work well for the majority of applications.

<a name="session-usage"></a>
## Session Usage

**Storing An Item In The Session**

	Session::put('key', 'value');

**Retrieving An Item From The Session**

	$value = Session::get('key');

**Retrieving An Item Or Returning A Default Value**

	$value = Session::get('key', 'default');

	$value = Session::get('key', function() { return 'default'; });

**Determining If An Item Exists In The Session**

	if (Session::has('users'))
	{
		//
	}

**Removing An Item From The Session**

	Session::forget('key');

**Removing All Items From The Session**

	Session::flush();

**Regenerating The Session ID**

	Session::regenerate();

<a name="flash-data"></a>
## Flash Data

Sometimes you may wish to store items in the session only for the next request. You may do so using the `Session::flash` method:

	Session::flash('key', 'value');

**Reflashing The Current Flash Data For Another Request**

	Session::reflash();

**Reflashing Only A Subset Of Flash Data**

	Session::keep(['username', 'email']);

<a name="database-sessions"></a>
## Database Sessions

When using the `database` session driver, you will need to setup a table to contain the session items. Below is an example `Schema` declaration for the table:

	Schema::create('sessions', function($t)
	{
		$t->string('id')->unique();
		$t->text('payload');
		$t->integer('last_activity');
	});

---

## File: templating.md

# Templating

- [Controller Layouts](#controller-layouts)
- [Blade Templating](#blade-templating)
- [Other Blade Control Structures](#other-blade-control-structures)

<a name="controller-layouts"></a>
## Controller Layouts

One method of using templates in Laravel is via controller layouts. By specifying the `layout` property on the controller, the view specified will be created for you and will be the assumed response that should be returned from actions.

**Defining A Layout On A Controller**

	class UserController extends BaseController {

		/**
		 * The layout that should be used for responses.
		 */
		protected $layout = 'layouts.master';

		/**
		 * Show the user profile.
		 */
		public function showProfile()
		{
			$this->layout->content = View::make('user.profile');
		}

	}

<a name="blade-template-engine"></a>
## Blade Templating

Blade is a simple, yet powerful templating engine provided with Laravel. Unlike controller layouts, Blade is driven by _template inheritance_ and _sections_. All Blade templates should use the `.blade.php` extension.

**Defining A Blade Layout**

	// Stored in app/views/layouts/master.blade.php

	<html>
		
			@section('sidebar')
				This is the master sidebar.
			@stop

			
				@yield('content')
			
		
	</html>

**Using A Blade Layout**

	@extends('layouts.master')

	@section('sidebar')
		@parent

		This is appended to the master sidebar.
	@stop

	@section('content')
		This is my body content.
	@stop

Note that views which `extend` a Blade layout simply override sections from the layout. Content of the layout can be included in a child view using the `@parent` directive in a section, allowing you to append to the contents of a layout section such as a sidebar or footer.

<a name="other-blade-control-structures"></a>
## Other Blade Control Structures

**Echoing Data**

	Hello, {{ $name }}.

	The current UNIX timestamp is {{ time() }}.

**If Statements**

	@if (count($records) > 0)
		I have records!
	@else
		I don't have any records!
	@endif

	@unless (Auth::check())
		You are not signed in.
	@endunless

**Loops**

	@for ($i = 0; $i < 10; $i++)
		The current value is {{ $i }}
	@endfor

	@foreach ($users as $user)
		This is user {{ $user->id }}
	@endforeach

	@while (true)
		I'm looping forever.
	@endwhile

**Including Sub-Views**

	@include('view.name')

**Comments**

	{{-- This comment will not be in the rendered HTML --}}

---

## File: testing.md

# Unit Testing

- [Introduction](#introduction)
- [Defining & Running Tests](#defining-and-running-tests)
- [Test Environment](#test-environment)
- [Calling Routes From Tests](#calling-routes-from-tests)
- [Helper Methods](#helper-methods)

<a name="introduction"></a>
## Introduction

Laravel is built with unit testing in mind. In fact, support for testing with PHPUnit is included out of the box, and a `phpunit.xml` file is already setup for your application. In addition to PHPUnit, Laravel also utilizes the Symfony HttpKernel, DomCrawler, and BrowserKit components to allow you to inspect and manipulate your views while testing, allowing to simulate a web browser.

An example test file is provided in the `app/tests` directory. After installing a new Laravel application, simply run `phpunit` on the command line to run your tests.

<a name="defining-and-running-tests"></a>
## Defining & Running Tests

To create a test case, simply create a new test file in the `app/tests` directory. The test class should extend `TestCase`. You may then define test methods as you normally would when using PHPUnit.

**An Example Test Class**

	class FooTest extends TestCase {

		public function testSomethingIsTrue()
		{
			$this->assertTrue(true);
		}

	}

You may run all of the tests for your application by executing the `phpunit` command from your terminal.

> **Note:** If you define your own `setUp` method, be sure to call `parent::setUp`.

<a name="test-environment"></a>
## Test Environment

When running unit tests, Laravel will automatically set the configuration environment to `testing`. Also, Laravel includes configuration files for `session` and `cache` in the test environment. Both of these drivers are set to `array` while in the test environment, meaning no session or cache data will be persisted while testing. You are free to create other testing environment configurations as necessary.

<a name="calling-routes-from-tests"></a>
## Calling Routes From Tests

You may easily call one of your routes for a test using the `call` method:

**Calling A Route From A Test**

	$response = $this->call('GET', 'user/profile');

	$response = $this->call($method, $uri, $parameters, $files, $server, $content);

You may then inspect the `Illuminate\Http\Response` object:

	$this->assertEquals('Hello World', $response->getContent());

You may also call a controller from a test:

**Calling A Controller From A Test**

	$response = $this->action('GET', 'HomeController@index');

	$response = $this->action('GET', 'UserController@profile', ['user' => 1]);

The `getContent` method will return the evaluated string contents of the response. If your route returns a `View`, you may access it using the `original` property:

	$view = $response->original;

	$this->assertEquals('John', $view['name']);

### DOM Crawler

You may also call a route and receive a DOM Crawler instance that you may use to inspect the content:

	$crawler = $this->client->request('GET', '/');

	$this->assertTrue($this->client->getResponse()->isOk());

	$this->assertCount(1, $crawler->filter('h1:contains("Hello World!")'));

For more information on how to use the crawler, refer to its [official documentation](http://symfony.com/doc/master/components/dom_crawler.html).

<a name="helper-methods"></a>
## Helper Methods

The `TestCase` class contains several helper methods to make testing your application easier.

You may set the currently authenticated user using the `be` method:

**Setting The Currently Authenticated User**

	$user = new User(['name' => 'John']);

	$this->be($user);

You may re-seed your database from a test using the `seed` method:

**Re-Seeding Database From Tests**

	$this->seed();

	$this->seed($connection);

More information on creating seeds may be found in the [migrations and seeding](/docs/migrations#database-seeding) section of the documentation.

---

## File: validation.md

# Validation

- [Basic Usage](#basic-usage)
- [Working With Error Messages](#working-with-error-messages)
- [Error Messages & Views](#error-messages-and-views)
- [Available Validation Rules](#available-validation-rules)
- [Custom Error Messages](#custom-error-messages)
- [Custom Validation Rules](#custom-validation-rules)

<a name="basic-usage"></a>
## Basic Usage

Laravel ships with a simple, convenient facility for validating data and retrieving validation error messages via the `Validation` class.

**Basic Validation Example**

	$validator = Validator::make(
		array('name' => 'Dayle'),
		array('name' => 'required|min:5')
	);

The first argument passed to the `make` method is the data under validation. The second argument are the validation rules that should be applied to the data.

Multiple rules may be delimited using either a "pipe" character, or as separate elements of an array.

**Using Arrays To Specify Rules**

	$validator = Validator::make(
		array('name' => 'Dayle'),
		array('name' => array('required', 'min:5'))
	);

Once the a `Validator` instance has been created, the `fails` (or `passes`) method may be used to perform the validation.

	if ($validation->fails())
	{
		// The given data did not pass validation
	}

If validation has failed, you may retrieve the error messages from the validator.

	$messages = $validator->messages();

**Validating Files**

The `Validator` class provides several rules for validating files, such as `size`, `mimes`, and others. When validating files, you may simply pass them into the validator with your other data.

<a name="working-with-error-messages"></a>
## Working With Error Messages

After calling the `messages` method on a `Validator` instance, you will receive a `MessageBag` instance, which has a variety of convenient methods for working with error messages.

**Retrieving The First Error Message For A Field**

	echo $messages->first('email');

**Retrieving All Error Messages For A Field**

	foreach ($messages->get('email') as $message)
	{
		//
	}

**Retrieving All Error Messages For All Fields**

	foreach ($messages->all() as $message)
	{
		//
	}

**Determining If Messages Exist For A Field**

	if ($messages->has('email'))
	{
		//
	}

**Retrieving An Error Message With A Format**

	echo $messages->first('email', ':message');

> **Note:** By default, messages are formatted using Bootstrap compatible syntax.

**Retrieving All Error Messages With A Format**

	foreach ($messages->all('<li>:message</li>') as $message)
	{
		//
	}

<a name="error-messages-and-views"></a>
## Error Messages & Views

Once you have performed validation, you will need an easy way to get the error messages back to your views. This is conveniently handled by Laravel. Consider the following routes as an example:

	Route::get('register', function()
	{
		return View::make('user.register');
	});

	Route::post('register', function()
	{
		$rules = [...];

		$validator = Validator::make(Input::all(), $rules);

		if ($validator->fails())
		{
			return Redirect::to('register')->withErrors($validator);
		}
	});

Note that when validation fails, we pass the `Validator` instance to the Redirect using the `withErrors` method. This method will flash the error messages to the session so that they are available on the next request.

However, notice that we do not have to explicitly bind the error messages to the view in our GET route. This is because Laravel will always check for errors in the session data, and automatically bind them to the view if they are available. **So, it is important to note that an `$errors` variable will always be available in all of your views, on every request**, allowing you to conveniently assume the `$errors` variable is always defined and can be safely used. The `$errors` variable will be an instance of `MessageBag`.

So, after redirection, you may utilize the automatically bound `$errors` variable in your view:

	<?php echo $errors->first('email'); ?>

<a name="available-validation-rules"></a>
## Available Validation Rules

Below is a list of all available validation rules and their function:

- [Accepted](#rule-accepted)
- [Active URL](#rule-active-url)
- [After (Date)](#rule-after)
- [Alpha](#rule-alpha)
- [Alpha Dash](#rule-alpha-dash)
- [Alpha Numeric](#rule-alpha-num)
- [Before (Date)](#rule-before)
- [Between](#rule-between)
- [Confirmed](#rule-confirmed)
- [Different](#rule-different)
- [E-Mail](#rule-email)
- [Exists (Database)](#rule-exists)
- [Image (File)](#rule-image)
- [In](#rule-in)
- [Integer](#rule-integer)
- [IP Address](#rule-ip)
- [Max](#rule-max)
- [MIME Types](#rule-mimes)
- [Min](#rule-min)
- [Numeric](#rule-numeric)
- [Regular Expression](#rule-regex)
- [Required](#rule-required)
- [Required With](#rule-required-with)
- [Same](#rule-same)
- [Size](#rule-size)
- [Unique (Database)](#rule-unique)
- [URL](#rule-url)

<a name="rule-accepted"></a>
#### accepted

The field under validation must be _yes_, _on_, or _1_. This is useful for validation "Terms of Service" acceptance.

<a name="rule-active-url"></a>
#### active_url

The field under validation must be a valid URL according to the `checkdnsrr` PHP function.

<a name="rule-after"></a>
#### after:_date_

The field under validation must be a value after a given date. The dates will be passed into the PHP `strtotime` function.

<a name="rule-alpha"></a>
#### alpha

The field under validation must be entirely alphabetic characters.

<a name="rule-alpha-dash"></a>
#### alpha_dash

The field under validation may have alpha-numeric characters, as well as dashes and underscores.

<a name="rule-alpha-num"></a>
#### alpha_num

The field under validation must be entirely alpha-numeric characters.

<a name="rule-before"></a>
#### before:_date_

The field under validation must be a value preceding the given date. The dates will be passed into the PHP `strtotime` function.

<a name="rule-between"></a>
#### between:_min_,_max_

The field under validation must have a size between the given _min_ and _max_. Strings, numerics, and files are evaluated in the same fashion as the `size` rule.

<a name="rule-confirmed"></a>
#### confirmed

The field under validation must have a matching field of `foo_confirmation`. For example, if the field under validation is `password`, a matching `password_confirmation` field must be present in the input.

<a name="rule-different"></a>
#### different:_field_

The given _field_ must be different than the field under validation.

<a name="rule-email"></a>
#### email

The field under validation must be formatted as an e-mail address.

<a name="rule-exists"></a>
#### exists:_table_,_column_

The field under validation must exists on a given database table.

**Basic Usage Of Exists Rule**

	'state' => 'exists:states'

**Specifying A Custom Column Name**

	'state' => 'exists:states,abbreviation'

<a name="rule-image"></a>
#### image

The file under validation must be an image (jpg, png, bmp, or gif)

<a name="rule-in"></a>
#### in:_foo_,_bar_,...

The field under validation must be included in the given list of values.

<a name="rule-integer"></a>
#### integer

The field under validation must have an integer value.

<a name="rule-ip"></a>
#### ip

The field under validation must be formatted as an IP address.

<a name="rule-max"></a>
#### max:_value_

The field under validation must be less than a maximum _value_. Strings, numerics, and files are evaluated in the same fashion as the `size` rule.

<a name="rule-mimes"></a>
#### mimes:_foo_,_bar_,...

The file under validation must have a MIME type corresponding to one of the listed extensions.

**Basic Usage Of MIME Rule**

	'photo' => 'mimes:jpg,bmp,png'

<a name="rule-min"></a>
#### min:_value_

The field under validation must have a minimum _value_. Strings, numerics, and files are evaluated in the same fashion as the `size` rule.

<a name="rule-numeric"></a>
#### numeric

The field under validation must have a numeric value.

<a name="rule-regex"></a>
#### regex:_pattern_

The field under validation must match the given regular expression.

**Note:** When using the `regex` pattern, it may be necessary to specify rules in an array instead of using pipe delimiters, especially if the regular expression contains a pipe character.

<a name="rule-required"></a>
#### required

The field under validation must be present in the input data.

<a name="rule-required-with"></a>
#### required_with:_foo_,_bar_,...

The field under validation must be present _only if_ the other specified fields are present.

<a name="rule-same"></a>
#### same:_field_

The given _field_ must match the field under validation.

<a name="rule-size"></a>
#### size:_value_

The field under validation must have a size matching the given _value_. For string data, _value_ corresponds to the number of characters. For numeric data, _value_ corresponds to a given integer value. For files, _size_ corresponds to the file size in kilobytes.

<a name="rule-unique"></a>
#### unique:_table_,_column_,_except_,_idColumn_

The field under validation must be unique on a given database table. If the `column` option is not specified, the field name will be used.

**Basic Usage Of Unique Rule**

	'email' => 'unique:users'

**Specifying A Custom Column Name**

	'email' => 'unique:users,email_address'

**Forcing A Unique Rule To Ignore A Given ID**

	'email' => 'unique:users,email_address,10'

<a name="rule-url"></a>
#### url

The field under validation must be formatted as an URL.

<a name="custom-error-messages"></a>
## Custom Error Messages

If needed, you may use custom error messages for validation instead of the defaults. There are several ways to specify custom messages.

**Passing Custom Messages Into Validator**

	$messages = [
		'required' => 'The :attribute field is required.',
	];

	$validator = Validator::make($input, $rules, $messages);

*Note:* The `:attribute` place-holder will be replaced by the actual name of the field under validation. You may also utilize other place-holders in validation messages.

**Other Validation Place-Holders**

	$messages = array(
		'same'    => 'The :attribute and :other must match.',
		'size'    => 'The :attribute must be exactly :size.',
		'between' => 'The :attribute must be between :min - :max.',
		'in'      => 'The :attribute must be one of the following types: :values',
	);

Sometimes you may wish to specify a custom error messages only for a specific field:

**Specifying A Custom Message For A Given Attribute**

	$messages = array(
		'email.required' => 'We need to know your e-mail address!',
	);

In some cases, you may wish to specify your custom messages in a language file instead of passing them directly to the `Validator`. To do so, add your messages to `custom` array in the `app/lang/xx/validation.php` language file.

**Specifying Custom Messages In Language Files**

	'custom' => array(
		'email' => array(
			'required' => 'We need to know your e-mail address!',
		),
	),

<a name="custom-validation-rules"></a>
## Custom Validation Rules

Laravel provides a variety of helpful validation rules; however, you may wish to specify some of your own. One method of registering custom validation rules is using the `Validator::extend` method:

**Registering A Custom Validation Rule**

	Validator::extend('foo', function($attribute, $value, $parameters)
	{
		return $value == 'foo'
	});

The custom validator Closure receives three arguments: the name of the `$attribute` being validated, the `$value` of the attribute, and an array of `$parameters` passed to the rule.

Note that you will also need to define an error message for your custom rules. You can do so either using an inline custom message array or by adding an entry in the validation language file.

Instead of using Closure callbacks to extend the Validator, you may also extend the Validator class itself. To do so, write a Validator class that extends `Illuminate\Validation\Validator`. You may add validation methods to the class by prefixing them with `validate`:

**Extending The Validator Class**

	<?php

	class CustomValidator extends Illuminate\Validation\Validator {

		public function validateFoo($attribute, $value, $parameters)
		{
			return $value == 'foo';
		}

	}

Next, you need to register your custom Validator extension:

**Registering A Custom Validator Resolver**

	Validator::resolver(function()
	{
		return new CustomValidator;
	});

When creating a custom validation rules, you may sometimes need to define custom place-holder replacements for error messages. You may do so by creating a custom Validator as described above, and adding a `replaceXXX` function to the validator.

	protected function replaceFoo($message, $attribute, $rule, $parameters)
	{
		return str_replace(':foo', $parameters[0], $message);
	}