Commit 6dd80636 authored by Taylor Otwell's avatar Taylor Otwell

adding doc routes.

parent 2a49787e
This diff is collapsed.
<?php
require_once __DIR__.'/libraries/markdown.php';
View::composer('docs::template', function($view)
{
Asset::add('stylesheet', 'css/style.css');
Asset::add('modernizr', 'js/modernizr-2.5.3.min.js');
Asset::container('footer')->add('prettify', 'js/prettify.js');
$view->with('sidebar', Markdown(file_get_contents(path('storage').'documentation/contents.md')));
});
Route::get('(:bundle)', function()
{
return View::make('docs::home');
});
Route::get('docs/(:any)/(:any?)', function($section, $page = null)
{
$page = rtrim(implode('/', array($section, $page)), '/').'.md';
$content = Markdown(file_get_contents(path('storage').'documentation/'.$page));
return View::make('docs::page')->with('content', $content);
});
\ No newline at end of file
@layout('docs::template')
@section('content')
{{ $content }}
@endsection
......@@ -22,7 +22,7 @@
</header>
<div role="main" class="main">
<aside class="sidebar">
@include('docs::menu')
{{ $sidebar }}
</aside>
<div class="content">
@yield('content')
......
......@@ -356,7 +356,7 @@ class View implements ArrayAccess {
}
else
{
return static::$cache[$this->path] = include $this->path;
return static::$cache[$this->path] = file_get_contents($this->path);
}
}
......
# Artisan Commands
## Contents
- [Application Configuration](#application-configuration)
- [Sessions](#sessions)
- [Migrations](#migrations)
- [Bundles](#bundles)
- [Tasks](#tasks)
- [Unit Tests](#unit-tests)
- [Routing](#routing)
- [Application Keys](#keys)
- [CLI Options](#cli-options)
<a name="application-configuration"></a>
## Application Configuration <small>[(More Information)](/docs/install#basic-configuration)</small>
Description | Command
------------- | -------------
Generate a secure application key. An application key will not be generated unless the field in **config/application.php** is empty. | `php artisan key:generate`
<a name="sessions"></a>
## Database Sessions <small>[(More Information)](/docs/session/config#database)</small>
Description | Command
------------- | -------------
Create a session table | `php artisan session:table`
<a name="migrations"></a>
## Migrations <small>[(More Information)](/docs/database/migrations)</small>
Description | Command
------------- | -------------
Create the Laravel migration table | `php artisan migrate:install`
Creating a migration | `php artisan migrate:make create_users_table`
Creating a migration for a bundle | `php artisan migrate:make bundle::tablename`
Running outstanding migrations | `php artisan migrate`
Running outstanding migrations in the application | `php artisan migrate application`
Running all outstanding migrations in a bundle | `php artisan migrate bundle`
Rolling back the last migration operation | `php artisan migrate:rollback`
Roll back all migrations that have ever run | `php artisan migrate:reset`
<a name="bundles"></a>
## Bundles <small>[(More Information)](/docs/bundles)</small>
Description | Command
------------- | -------------
Install a bundle | `php artisan bundle:install eloquent`
Upgrade a bundle | `php artisan bundle:upgrade eloquent`
Upgrade all bundles | `php artisan bundle:upgrade`
Publish a bundle assets | `php artisan bundle:publish bundle_name`
Publish all bundles assets | `php artisan bundle:publish`
<br>
> **Note:** After installing you need to [register the bundle](../bundles/#registering-bundles)
<a name="tasks"></a>
## Tasks <small>[(More Information)](/docs/artisan/tasks)</small>
Description | Command
------------- | -------------
Calling a task | `php artisan notify`
Calling a task and passing arguments | `php artisan notify taylor`
Calling a specific method on a task | `php artisan notify:urgent`
Running a task on a bundle | `php artisan admin::generate`
Running a specific method on a bundle | `php artisan admin::generate:list`
<a name="unit-tests"></a>
## Unit Tests <small>[(More Information)](/docs/testing)</small>
Description | Command
------------- | -------------
Running the application tests | `php artisan test`
Running the bundle tests | `php artisan test bundle-name`
<a name="routing"></a>
## Routing <small>[(More Information)](/docs/routing)</small>
Description | Command
------------- | -------------
Calling a route | `php artisan route:call get api/user/1`
<br>
> **Note:** You can replace get with post, put, delete, etc.
<a name="keys"></a>
## Application Keys
Description | Command
------------- | -------------
Generate an application key | `php artisan key:generate`
<br>
> **Note:** You can specify an alternate key length by adding an extra argument to the command.
<a name="cli-options"></a>
## CLI Options
Description | Command
------------- | -------------
Setting the Laravel environment | `php artisan foo --env=local`
Setting the default database connection | `php artisan foo --database=sqlitename`
# Tasks
## Contents
- [The Basics](#the-basics)
- [Creating & Running Tasks](#creating-tasks)
- [Bundle Tasks](#bundle-tasks)
- [CLI Options](#cli-options)
<a name="the-basics"></a>
## The Basics
Laravel's command-line tool is called Artisan. Artisan can be used to run "tasks" such as migrations, cronjobs, unit-tests, or anything that want.
<a name="creating-tasks"></a>
## Creating & Running Tasks
To create a task create a new class in your **application/tasks** directory. The class name should be suffixed with "_Task", and should at least have a "run" method, like this:
#### Creating a task class:
class Notify_Task {
public function run($arguments)
{
// Do awesome notifying...
}
}
Now you can call the "run" method of your task via the command-line. You can even pass arguments:
#### Calling a task from the command line:
php artisan notify
#### Calling a task and passing arguments:
php artisan notify taylor
Remember, you can call specific methods on your task, so, let's add an "urgent" method to the notify task:
#### Adding a method to the task:
class Notify_Task {
public function run($arguments)
{
// Do awesome notifying...
}
public function urgent($arguments)
{
// This is urgent!
}
}
Now we can call our "urgent" method:
#### Calling a specific method on a task:
php artisan notify:urgent
<a name="bundle-tasks"></a>
## Bundle Tasks
To create a task for your bundle just prefix the bundle name to the class name of your task. So, if your bundle was named "admin", a task might look like this:
#### Creating a task class that belongs to a bundle:
class Admin_Generate_Task {
public function run($arguments)
{
// Generate the admin!
}
}
To run your task just use the usual Laravel double-colon syntax to indicate the bundle:
#### Running a task belonging to a bundle:
php artisan admin::generate
#### Running a specific method on a task belonging to a bundle:
php artisan admin::generate:list
<a name="cli-options"></a>
## CLI Options
#### Setting the Laravel environment:
php artisan foo --env=local
#### Setting the default database connection:
php artisan foo --database=sqlite
\ No newline at end of file
# Auth Configuration
## Contents
- [The Basics](#the-basics)
- [The User Function](#user)
- [The Attempt Function](#attempt)
- [The Logout Function](#logout)
<a name="the-basics"></a>
## The Basics
Most interactive applications have the ability for users to login and logout. Laravel provides a simple class to help you validate user credentials and retrieve information about the current user of your application.
To get started, let's look over the **application/config/auth.php** file. The authentication configuration contains three functions: **user**, **attempt**, and **logout**. Let's go over each one individually.
<a name="user"></a>
## The "User" Function
The **user** function is called when Laravel needs to retrieve the currently logged in user of your application. When a user logs into your application, Laravel stores the ID of that user in the [session](/docs/session/config). So, on subsequent requests, we can use the ID stored in the session to retrieve the user's information from storage. However, applications use various data stores. For this reason, you are given complete flexibility regarding how to retrieve the user.
Of course, a simple default configuration has been setup for you. Let's take a look:
'user' => function($id)
{
if ( ! is_null($id) and filter_var($id, FILTER_VALIDATE_INT) !== false)
{
return DB::table('users')->find($id);
}
}
As you probably noticed, the user's ID is passed to the function. The default configuration utilizes the [fluent query builder](/docs/database/fluent) to retrieve and return the user from the database. Of course, you are free to use other methods of retrieving the user. If no user is found in storage for the given ID, the function should simply return **null**.
<a name="attempt"></a>
## The "Attempt" Function
Anytime you need to validate the credentials of a user, the **attempt** function is called. When attempting to authenticate a user, you will typically retrieve the user out of storage, and check the hashed password against the given password. However, since applications may use various methods of hashing or even third-party login providers, you are free to implement the authentication however you wish. Again, a simple and sensible default has been provided:
'attempt' => function($username, $password)
{
$user = DB::table('users')->where_username($username)->first();
if ( ! is_null($user) and Hash::check($password, $user->password))
{
return $user;
}
}
Like the previous example, the fluent query builder is used to retrieve the user out of the database by the given username. If the user is found, the given password is hashed and compared against the hashed password stored on the table, and if the passwords match, the user model is returned. If the credentials are invalid or the user does not exist, **null** should be returned.
> **Note:** Any object may be returned by this function as long as it has an **id** property.
<a name="logout"></a>
## The "Logout" Function
The **logout** function is called whenever a user is logged out of your application. This function gives you a convenient location to interact with any third-party authentication providers you may be using.
\ No newline at end of file
# Authentication Usage
## Contents
- [Salting & Hashing](#hash)
- [Logging In](#login)
- [Protecting Routes](#filter)
- [Retrieving The Logged In User](#user)
- [Logging Out](#logout)
> **Note:** Before using the Auth class, you must [specify a session driver](/docs/session/config).
<a name="hash"></a>
## Salting & Hashing
If you are using the Auth class, you are strongly encouraged to hash and salt all passwords. Web development must be done responsibly. Salted, hashed passwords make a rainbow table attack against your user's passwords impractical.
Salting and hashing passwords is done using the **Hash** class. The Hash class is uses the **bcrypt** hashing algorithm. Check out this example:
$password = Hash::make('secret');
The **make** method of the Hash class will return a 60 character hashed string.
You can compare an unhashed value against a hashed one using the **check** method on the **Hash** class:
if (Hash::check('secret', $hashed_value))
{
return 'The password is valid!';
}
<a name="login"></a>
## Logging In
Logging a user into your application is simple using the **attempt** method on the Auth class. Simply pass the username and password of the user to the method. The login method will return **true** if the credentials are valid. Otherwise, **false** will be returned:
if (Auth::attempt('example@gmail.com', 'password'))
{
return Redirect::to('user/profile');
}
If the user's credentials are valid, the user ID will be stored in the session and the user will be considered "logged in" on subsequent requests to your application.
You probably noticed this method name corresponds to the **attempt** function you [configured earlier](/docs/auth/config#attempt). Each time you call the **attempt** method on the **Auth** class, the **attempt** function in the configuration file will be called to check the user's credentials.
> **Note:** To provide more flexiblity when working with third-party authentication providers, you are not required to pass a password into the **attempt** method.
To determine if the user of your application is logged in, call the **check** method:
if (Auth::check())
{
return "You're logged in!";
}
Use the **login** method to login a user without checking their credentials, such as after a user first registers to use your application. Just pass your user object or the user's ID:
Auth::login($user);
Auth::login(15);
<a name="filter"></a>
## Protecting Routes
It is common to limit access to certain routes only to logged in users. In Laravel this is accomplished using the [auth filter](/docs/routing#filters). If the user is logged in, the request will proceed as normal; however, if the user is not logged in, they will be redirected to the "login" [named route](/docs/routing#named-routes).
To protect a route, simply attach the **auth** filter:
Route::get('admin', array('before' => 'auth', function() {});
> **Note:** You are free to edit the **auth** filter however you like. A default implementation is located in **application/routes.php**.
<a name="user"></a>
## Retrieving The Logged In User
Once a user has logged in to your application, you can access the user model via the **user** method on the Auth class:
return Auth::user()->email;
This method calls the [**user** function](/docs/auth/config#user) in the configuration file. Also, you don't need to worry about performance when using this method. The user is only retrieved from storage the first time you use the method.
> **Note:** If the user is not logged in, the **user** method will return NULL.
<a name="logout"></a>
## Logging Out
Ready to log the user out of your application?
Auth::logout();
This method will remove the user ID from the session, and the user will no longer be considered logged in on subsequent requests to your application.
\ No newline at end of file
# Bundles
## Contents
- [The Basics](#the-basics)
- [Creating Bundles](#creating-bundles)
- [Registering Bundles](#registering-bundles)
- [Bundles & Class Loading](#bundles-and-class-loading)
- [Starting Bundles](#starting-bundles)
- [Routing To Bundles](#routing-to-bundles)
- [Using Bundles](#using-bundles)
- [Bundle Assets](#bundle-assets)
- [Installing Bundles](#installing-bundles)
- [Upgrading Bundles](#upgrading-bundles)
<a name="the-basics"></a>
## The Basics
Bundles are the heart of the improvements that were made in Laravel 3.0. They are a simple way to group code into convenient "bundles". A bundle can have it's own views, configuration, routes, migrations, tasks, and more. A bundle could be everything from a database ORM to a robust authentication system. Modularity of this scope is an important aspect that has driven virtually all design decisions within Laravel. In many ways you can actually think of the application folder as the special default bundle with which Laravel is pre-programmed to load and use.
<a name="creating-and-registering"></a>
## Creating Bundles
The first step in creating a bundle is to create a folder for the bundle within your **bundles** directory. For this example, let's create an "admin" bundle, which could house the administrator back-end to our application. The **application/start.php** file provides some basic configuration that helps to define how our application will run. Likewise we'll create a **start.php** file within our new bundle folder for the same purpose. It is run everytime the bundle is loaded. Let's create it:
#### Creating a bundle start.php file:
<?php
Autoloader::namespaces(array(
'Admin' => Bundle::path('admin').'models',
));
In this start file we've told the auto-loader that classes that are namespaced to "Admin" should be loaded out of our bundle's models directory. You can do anything you want in your start file, but typically it is used for registering classes with the auto-loader. **In fact, you aren't required to create a start file for your bundle.**
Next, we'll look at how to register this bundle with our application!
<a name="registering-bundles"></a>
## Registering Bundles
Now that we have our admin bundle, we need to register it with Laravel. Pull open your **application/bundles.php** file. This is where you register all bundles used by your application. Let's add ours:
#### Registering a simple bundle:
return array('admin'),
By convention, Laravel will assume that the Admin bundle is located at the root level of the bundle directory, but we can specify another location if we wish:
#### Registering a bundle with a custom location:
return array(
'admin' => array('location' => 'userscape/admin'),
);
Now Laravel will look for our bundle in **bundles/userscape/admin**.
<a name="bundles-and-class-loading"></a>
## Bundles & Class Loading
Typically, a bundle's **start.php** file only contains auto-loader registrations. So, you may want to just skip **start.php** and declare your bundle's mappings right in its registration array. Here's how:
#### Defining auto-loader mappings in a bundle registration:
return array(
'admin' => array(
'autoloads' => array(
'map' => array(
'Admin' => '(:bundle)/admin.php',
),
'namespaces' => array(
'Admin' => '(:bundle)/lib',
),
'directories' => array(
'(:bundle)/models',
),
),
),
);
Notice that each of these options corresponds to a function on the Laravel [auto-loader](/docs/loading). In fact, the value of the option will automatically be passed to the corresponding function on the auto-loader.
You may have also noticed the **(:bundle)** place-holder. For convenience, this will automatically be replaced with the path to the bundle. It's a piece of cake.
<a name="starting-bundles"></a>
## Starting Bundles
So our bundle is created and registered, but we can't use it yet. First, we need to start it:
#### Starting a bundle:
Bundle::start('admin');
This tells Laravel to run the **start.php** file for the bundle, which will register its classes in the auto-loader. The start method will also load the **routes.php** file for the bundle if it is present.
> **Note:** The bundle will only be started once. Subsequent calls to the start method will be ignored.
If you use a bundle throughout your application, you may want it to start on every request. If this is the case, you can configure the bundle to auto-start in your **application/bundles.php** file:
#### Configuration a bundle to auto-start:
return array(
'admin' => array('auto' => true),
);
You do not always need to explicitly start a bundle. In fact, you can usually code as if the bundle was auto-started and Laravel will take care of the rest. For example, if you attempt to use a bundle views, configurations, languages, routes or filters, the bundle will automatically be started!
Each time a bundle is started, it fires an event. You can listen for the starting of bundles like so:
#### Listen for a bundle's start event:
Event::listen('laravel.started: admin', function()
{
// The "admin" bundle has started...
});
It is also possible to "disable" a bundle so that it will never be started.
#### Disabling a bundle so it can't be started:
Bundle::disable('admin');
<a name="routing-to-bundles"></a>
## Routing To Bundles
Refer to the documentation on [bundle routing](/docs/routing#bundle-routes) and [bundle controllers](/docs/controllers#bundle-controllers) for more information on routing and bundles.
<a name="using-bundles"></a>
## Using Bundles
As mentioned previously, bundles can have views, configuration, language files and more. Laravel uses a double-colon syntax for loading these items. So, let's look at some examples:
#### Loading a bundle view:
return View::make('bundle::view');
#### Loading a bundle configuration item:
return Config::get('bundle::file.option');
#### Loading a bundle language line:
return Lang::line('bundle::file.line');
Sometimes you may need to gather more "meta" information about a bundle, such as whether it exists, its location, or perhaps its entire configuration array. Here's how:
#### Determine whether a bundle exists:
Bundle::exists('admin');
#### Retrieving the installation location of a bundle:
$location = Bundle::path('admin');
#### Retrieving the configuration array for a bundle:
$config = Bundle::get('admin');
#### Retrieving the names of all installed bundles:
$names = Bundle::names();
<a name="bundle-assets"></a>
## Bundle Assets
If your bundle contains views, it is likely you have assets such as JavaScript and images that need to be available in the **public** directory of the application. No problem. Just create **public** folder within your bundle and place all of your assets in this folder.
Great! But, how do they get into the application's **public** folder. The Laravel "Artisan" command-line provides a simple command to copy all of your bundle's assets to the public directory. Here it is:
#### Publish bundle assets into the public directory:
php artisan bundle:publish
This command will create a folder for the bundle's assets within the application's **public/bundles** directory. For example, if your bundle is named "admin", a **public/bundles/admin** folder will be created, which will contain all of the files in your bundle's public folder.
For more information on conveniently getting the path to your bundle assets once they are in the public directory, refer to the documentation on [asset management](/docs/views/assets#bundle-assets).
<a name="installing-bundles"></a>
## Installing Bundles
Of course, you may always install bundles manually; however, the "Artisan" CLI provides an awesome method of installing and upgrading your bundle. The framework uses simple Zip extraction to install the bundle. Here's how it works.
#### Installing a bundle via Artisan:
php artisan bundle:install eloquent
Great! Now that you're bundle is installed, you're ready to [register it](#registering-bundles) and [publish its assets](#bundle-assets).
Need a list of available bundles? Check out the Laravel [bundle directory](http://bundles.laravel.com)
<a name="upgrading-bundles"></a>
## Upgrading Bundles
When you upgrade a bundle, Laravel will automatically remove the old bundle and install a fresh copy.
#### Upgrading a bundle via Artisan:
php artisan bundle:upgrade eloquent
> **Note:** After upgrading the bundle, you may need to [re-publish its assets](#bundle-assets).
**Important:** Since the bundle is totally removed on an upgrade, you must be aware of any changes you have made to the bundle code before upgrading. You may need to change some configuration options in a bundle. Instead of modifying the bundle code directly, use the bundle start events to set them. Place something like this in your **application/start.php** file.
#### Listening for a bundle's start event:
Event::listen('laravel.started: admin', function()
{
Config::set('admin::file.option', true);
});
\ No newline at end of file
# Cache Configuration
## Contents
- [The Basics](#the-basics)
- [Database](#database)
- [Memcached](#memcached)
- [Redis](#redis)
- [Cache Keys](#keys)
- [In-Memory Cache](#memory)
<a name="the-basics"></a>
## The Basics
Imagine your application displays the ten most popular songs as voted on by your users. Do you really need to look up these ten songs every time someone visits your site? What if you could store them for 10 minutes, or even an hour, allowing you to dramatically speed up your application? Laravel's caching makes it simple.
Laravel provides five cache drivers out of the box:
- File System
- Database
- Memcached
- APC
- Redis
- Memory (Arrays)
By default, Laravel is configured to use the **file** system cache driver. It's ready to go out of the box with no configuration. The file system driver stores cached items as files in the **cache** directory. If you're satisfied with this driver, no other configuration is required. You're ready to start using it.
> **Note:** Before using the file system cache driver, make sure your **storage/cache** directory is writeable.
<a name="database"></a>
## Database
The database cache driver uses a given database table as a simple key-value store. To get started, first set the name of the database table in **application/config/cache.php**:
'database' => array('table' => 'laravel_cache'),
Next, create the table on your database. The table should have three columns:
- key (varchar)
- value (text)
- expiration (integer)
That's it. Once your configuration and table is setup, you're ready to start caching!
<a name="memcached"></a>
## Memcached
[Memcached](http://memcached.org) is an ultra-fast, open-source distributed memory object caching system used by sites such as Wikipedia and Facebook. Before using Laravel's Memcached driver, you will need to install and configure Memcached and the PHP Memcache extension on your server.
Once Memcached is installed on your server you must set the **driver** in the **application/config/cache.php** file:
'driver' => 'memcached'
Then, add your Memcached servers to the **servers** array:
'servers' => array(
array('host' => '127.0.0.1', 'port' => 11211, 'weight' => 100),
)
<a name="redis"></a>
## Redis
[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).
Before using the Redis cache driver, you must [configure your Redis servers](/docs/database/redis#config). Now you can just set the **driver** in the **application/config/cache.php** file:
'driver' => 'redis'
<a name="keys"></a>
### Cache Keys
To avoid naming collisions with other applications using APC, Redis, or a Memcached server, Laravel prepends a **key** to each item stored in the cache using these drivers. Feel free to change this value:
'key' => 'laravel'
<a name="memory"></a>
### In-Memory Cache
The "memory" cache driver does not actually cache anything to disk. It simply maintains an internal array of the cache data for the current request. This makes it perfect for unit testing your application in isolation from any storage mechanism. It should never be used as a "real" cache driver.
\ No newline at end of file
# Cache Usage
## Contents
- [Storing Items](#put)
- [Retrieving Items](#get)
- [Removing Items](#forget)
<a name="put"></a>
## Storing Items
Storing items in the cache is simple. Simply call the **put** method on the Cache class:
Cache::put('name', 'Taylor', 10);
The first parameter is the **key** to the cache item. You will use this key to retrieve the item from the cache. The second parameter is the **value** of the item. The third parameter is the number of **minutes** you want the item to be cached.
You may also cache something "forever" if you do not want the cache to expire:
Cache::forever('name', 'Taylor');
> **Note:** It is not necessary to serialize objects when storing them in the cache.
<a name="get"></a>
## Retrieving Items
Retrieving items from the cache is even more simple than storing them. It is done using the **get** method. Just mention the key of the item you wish to retrieve:
$name = Cache::get('name');
By default, NULL will be returned if the cached item has expired or does not exist. However, you may pass a different default value as a second parameter to the method:
$name = Cache::get('name', 'Fred');
Now, "Fred" will be returned if the "name" cache item has expired or does not exist.
What if you need a value from your database if a cache item doesn't exist? The solution is simple. You can pass a closure into the **get** method as a default value. The closure will only be executed if the cached item doesn't exist:
$users = Cache::get('count', function() {return DB::table('users')->count();});
Let's take this example a step further. Imagine you want to retrieve the number of registered users for your application; however, if the value is not cached, you want to store the default value in the cache using the **remember** method:
$users = Cache::remember('count', function() {return DB::table('users')->count();}, 5);
Let's talk through that example. If the **count** item exists in the cache, it will be returned. If it doesn't exist, the result of the closure will be stored in the cache for five minutes **and** be returned by the method. Slick, huh?
Laravel even gives you a simple way to determine if a cached item exists using the **has** method:
if (Cache::has('name'))
{
$name = Cache::get('name');
}
<a name="forget"></a>
## Removing Items
Need to get rid of a cached item? No problem. Just mention the name of the item to the **forget** method:
Cache::forget('name');
\ No newline at end of file
# Runtime Configuration
## Contents
- [The Basics](#the-basics)
- [Retrieving Options](#retrieving-options)
- [Setting Options](#setting-options)
<a name="the-basics"></a>
## The Basics
Sometimes you may need to get and set configuration options at runtime. For this you'll use the **Config** class, which utilizes Laravel's "dot" syntax for accessing configuration files and items.
<a name="retrieving-options"></a>
## Retrieving Options
#### Retrieve a configuration option:
$value = Config::get('application.url');
#### Return a default value if the option doesn't exist:
$value = Config::get('application.timezone', 'UTC');
#### Retrieve an entire configuration array:
$options = Config::get('database');
<a name="setting-options"></a>
## Setting Options
#### Set a configuration option:
Config::set('cache.driver', 'apc');
\ No newline at end of file
### General
- [Laravel Overview](/docs/home)
- [Installation & Setup](/docs/install)
- [Requirements](/docs/install#requirements)
- [Installation](/docs/install#installation)
- [Basic Configuration](/docs/install#basic-configuration)
- [Environments](/docs/install#environments)
- [Cleaner URLs](/docs/install#cleaner-urls)
- [Controllers](/docs/controllers)
- [The Basics](/docs/controllers#the-basics)
- [Controller Routing](/docs/controllers#controller-routing)
- [Bundle Controllers](/docs/controllers#bundle-controllers)
- [Action Filters](/docs/controllers#action-filters)
- [Nested Controllers](/docs/controllers#nested-controllers)
- [RESTful Controllers](/docs/controllers#restful-controllers)
- [Dependency Injection](/docs/controllers#dependency-injection)
- [Controller Factory](/docs/controllers#controller-factory)
- [Models & Libraries](/docs/models)
- [Views & Responses](/docs/views)
- [The Basics](/docs/views#basics)
- [Binding Data To Views](/docs/views#binding-data-to-views)
- [Nesting Views](/docs/views#nesting-views)
- [Named Views](/docs/views#named-views)
- [View Composers](/docs/views#view-composers)
- [Redirects](/docs/views#redirects)
- [Redirecting With Data](/docs/views#redirecting-with-flash-data)
- [Downloads](/docs/views#downloads)
- [Errors](/docs/views#errors)
- [Managing Assets](/docs/views/assets)
- [Templating](/docs/views/templating)
- [Pagination](/docs/views/pagination)
- [Building HTML](/docs/views/html)
- [Building Forms](/docs/views/forms)
- [Routing](/docs/routing)
- [The Basics](/docs/routing#the-basics)
- [Wildcards](/docs/routing#wildcards)
- [The 404 Event](/docs/routing#the-404-event)
- [Filters](/docs/routing#filters)
- [Global Filters](/docs/routing#global-filters)
- [Route Groups](/docs/routing#groups)
- [Named Routes](/docs/routing#named-routes)
- [HTTPS Routes](/docs/routing#https-routes)
- [Bundle Routing](/docs/routing#bundle-routing)
- [CLI Route Testing](/docs/routing#cli-route-testing)
- [Input & Cookies](/docs/input)
- [Input](/docs/input#input)
- [Files](/docs/input#files)
- [Old Input](/docs/input#old-input)
- [Redirecting With Old Input](/docs/input#redirecting-with-old-input)
- [Cookies](/docs/input#cookies)
- [Bundles](/docs/bundles)
- [The Basics](/docs/bundles#the-basics)
- [Creating Bundles](/docs/bundles#creating-bundles)
- [Registering Bundles](/docs/bundles#registering-bundles)
- [Bundles & Class Loading](/docs/bundles#bundles-and-class-loading)
- [Starting Bundles](/docs/bundles#starting-bundles)
- [Routing To Bundles](/docs/bundles#routing-to-bundles)
- [Using Bundles](/docs/bundles#using-bundles)
- [Bundle Assets](/docs/bundles#bundle-assets)
- [Installing Bundles](/docs/bundles#installing-bundles)
- [Upgrading Bundles](/docs/bundles#upgrading-bundles)
- [Class Auto Loading](/docs/loading)
- [Errors & Logging](/docs/logging)
- [Runtime Configuration](/docs/config)
- [Examining Requests](/docs/requests)
- [Generating URLs](/docs/urls)
- [Events](/docs/events)
- [Validation](/docs/validation)
- [Working With Files](/docs/files)
- [Working With Strings](/docs/strings)
- [Localization](/docs/localization)
- [Encryption](/docs/encryption)
- [IoC Container](/docs/ioc)
- [Unit Testing](/docs/testing)
### Database
- [Configuration](/docs/database/config)
- [Raw Queries](/docs/database/raw)
- [Fluent Query Builder](/docs/database/fluent)
- [Eloquent ORM](/docs/database/eloquent)
- [Schema Builder](/docs/database/schema)
- [Migrations](/docs/database/migrations)
- [Redis](/docs/database/redis)
### Caching
- [Configuration](/docs/cache/config)
- [Usage](/docs/cache/usage)
### Sessions
- [Configuration](/docs/session/config)
- [Usage](/docs/session/usage)
### Authentication
- [Configuration](/docs/auth/config)
- [Usage](/docs/auth/usage)
### Artisan CLI
- [Tasks](/docs/artisan/tasks)
- [The Basics](/docs/artisan/tasks#the-basics)
- [Creating & Running Tasks](/docs/artisan/tasks#creating-tasks)
- [Bundle Tasks](/docs/artisan/tasks#bundle-tasks)
- [CLI Options](/docs/artisan/tasks#cli-options)
- [Commands](/docs/artisan/commands)
\ No newline at end of file
# Controllers
## Contents
- [The Basics](#the-basics)
- [Controller Routing](#controller-routing)
- [Bundle Controllers](#bundle-controllers)
- [Action Filters](#action-filters)
- [Nested Controllers](#nested-controllers)
- [Controller Layouts](#controller-layouts)
- [RESTful Controllers](#restful-controllers)
- [Dependency Injection](#dependency-injection)
- [Controller Factory](#controller-factory)
<a name="the-basics"></a>
## The Basics
Controllers are classes that are responsible for accepting user input and managing interactions between models, libraries, and views. Typically, they will ask a model for data, and then return a view that presents that data to the user.
The usage of controllers is the most common method of implementingapplication logic in modern web-development. However, Laravel also empowers developers to implement their application logic within routing declarations. This is explored in detail in the [routing document](/docs/routing). New users are encourage to start with controllers. There is nothing that route-based application logic can do that controllers can't.
Controller classes should be stored in **application/controllers** and should extend the Base\_Controller class. A Home\_Controller class is included with Laravel.
#### Creating a simple controller:
class Admin_Controller extends Base_Controller
{
public function action_index()
{
//
}
}
**Actions** are the name of controller methods that are intended to be web-accessible. Actions should be prefixed with "action\_". All other methods, regardless of scope, will not be web-accessible.
> **Note:** The Base\_Controller class extends the main Laravel Controller class, and gives you a convenient place to put methods that are common to many controllers.
<a name="controller-routing"></a>
## Controller Routing
It is important to be aware that all routes in Laravel must be explicitly defined, including routes to controllers.
This means that controller methods that have not been exposed through route registration **cannot** be accessed. It's possible to automatically expose all methods within a controller using controller route registration. Controller route registrations are typically defined in **application/routes.php**.
Check [the routing page](/docs/routing#controller-routing) for more information on routing to controllers.
<a name="bundle-controllers"></a>
## Bundle Controllers
Bundles are Laravel's modular package system. Bundles can easily configured to handle requests to your application. We'll be going over [bundles in more detail](/docs/bundles) in another document.
Creating controllers that belong to bundles is almost identical to creating your application controllers. Just prefix the controller class name with the name of the bundle, so if your bundle is named "admin", your controller classes would look like this:
#### Creating a bundle controller class:
class Admin_Home_Controller extends Base_Controller
{
public function action_index()
{
return "Hello Admin!";
}
}
But, how do you register a bundle controller with the router? It's simple. Here's what it looks like:
#### Registering a bundle's controller with the router:
Route::controller('admin::home');
Great! Now we can access our "admin" bundle's home controller from the web!
> **Note:** Throughout Laravel the double-colon syntax is used to denote bundles. More information on bundles can be found in the [bundle documentation](/docs/bundles).
<a name="action-filters"></a>
## Action Filters
Action filters are methods that can be run before or after a controller action. With Laravel you don't only have control over which filters are assigned to which actions. But, you can also choose which http verbs (post, get, put, and delete) will activate a filter.
You can assign "before" and "after" filters to controller actions within the controller's constructor.
#### Attaching a filter to all actions:
$this->filter('before', 'auth');
In this example the 'auth' filter will be run before every action within this controller. The auth action comes out-of-the-box with Laravel and can be found in **application/routes.php**. The auth filter verifies that a user is logged in and redirects them to 'login' if they are not.
#### Attaching a filter to only some actions:
$this->filter('before', 'auth')->only(array('index', 'list'));
In this example the auth filter will be run before the action_index() or action_list() methods are run. Users must be logged in before having access to these pages. However, no other actions within this controller require an authenticated session.
#### Attaching a filter to all except a few actions:
$this->filter('before', 'auth')->except(array('add', 'posts'));
Much like the previous example, this declaration ensures that the auth filter is run on only some of this controller's actions. Instead of declaring to which actions the filter applies we are instead declaring the actions that will not require authenticated sessions. It can sometimes be safer to use the 'except' method as it's possible to add new actions to this controller and to forget to add them to only(). This could potentially lead your controller's action being unintentionally accessible by users who haven't been authenticated.
#### Attaching a filter to run on POST:
$this->filter('before', 'csrf')->on('post');
This example shows how a filter can be run only on a specific http verb. In this case we're running the csrf filter only when a form post is made. The csrf filter is designed to prevent form posts from other systems (spam bots for example) and comes by default with Laravel. You can find the csrf filter in **application/routes.php**.
*Further Reading:*
- *[Route Filters](/docs/routing#filters)*
<a name="nested-controllers"></a>
## Nested Controllers
Controllers may be located within any number of sub-directories within the main **application/controllers** folder.
Define the controller class and store it in **controllers/admin/panel.php**.
class Admin_Panel_Controller extends Base_Controller
{
public function action_index()
{
//
}
}
#### Register the nested controller with the router using "dot" syntax:
Route::controller('admin.panel');
> **Note:** When using nested controllers, always register your controllers from most nested to least nested in order to avoid shadowing controller routes.
#### Access the "index" action of the controller:
http://localhost/admin/panel
<a name="controller-layouts"></a>
## Controller Layouts
Full documentation on using layouts with Controllers [can be found on the Templating page](http://laravel.com/docs/views/templating).
<a name="restful-controllers"></a>
## RESTful Controllers
Instead of prefixing controller actions with "action_", you may prefix them with the HTTP verb they should respond to.
#### Adding the RESTful property to the controller:
class Home_Controller extends Base_Controller
{
public $restful = true;
}
#### Building RESTful controller actions:
class Home_Controller extends Base_Controller
{
public $restful = true;
public function get_index()
{
//
}
public function post_index()
{
//
}
}
This is particularly useful when building CRUD methods as you can separate the logic which populates and renders a form from the logic that validates and stores the results.
<a name="dependency-injection"></a>
## Dependency Injection
If you are focusing on writing testable code, you will probably want to inject dependencies into the constructor of your controller. No problem. Just register your controller in the [IoC container](/docs/ioc). When registering the controller with the container, prefix the key with **controller**. So, in our **application/start.php** file, we could register our user controller like so:
IoC::register('controller: user', function()
{
return new User_Controller;
});
When a request to a controller enters your application, Laravel will automatically determine if the controller is registered in the container, and if it is, will use the container to resolve an instance of the controller.
> **Note:** Before diving into controller dependency injection, you may wish to read the documentation on Laravel's beautiful [IoC container](/docs/ioc).
<a name="controller-factory"></a>
## Controller Factory
If you want even more control over the instantiation of your controllers, such as using a third-party IoC container, you'll need to use the Laravel controller factory.
**Register an event to handle controller instantiation:**
Event::listen(Controller::factory, function($controller)
{
return new $controller;
});
The event will receive the class name of the controller that needs to be resolved. All you need to do is return an instance of the controller.
# Database Configuration
## Contents
- [Quick Start Using SQLite](#quick)
- [Configuring Other Databases](#server)
- [Setting The Default Connection Name](#default)
Laravel supports the following databases out of the box:
- MySQL
- PostgreSQL
- SQLite
- SQL Server
All of the database configuration options live in the **application/config/database.php** file.
<a name="quick"></a>
## Quick Start Using SQLite
[SQLite](http://sqlite.org) is an awesome, zero-configuration database system. By default, Laravel is configured to use a SQLite database. Really, you don't have to change anything. Just drop a SQLite database named **application.sqlite** into the **application/storage/database** directory. You're done.
Of course, if you want to name your database something besides "application", you can modify the database option in the SQLite section of the **application/config/database.php** file:
'sqlite' => array(
'driver' => 'sqlite',
'database' => 'your_database_name',
)
If your application receives less than 100,000 hits per day, SQLite should be suitable for production use in your application. Otherwise, consider using MySQL or PostgreSQL.
> **Note:** Need a good SQLite manager? Check out this [Firefox extension](https://addons.mozilla.org/en-US/firefox/addon/sqlite-manager/).
<a name="server"></a>
## Configuring Other Databases
If you are using MySQL, SQL Server, or PostgreSQL, you will need to edit the configuration options in **application/config/database.php**. In the configuration file you can find sample configurations for each of these systems. Just change the options as necessary for your server and set the default connection name.
<a name="default"></a>
## Setting The Default Connection Name
As you have probably noticed, each database connection defined in the **application/config/database.php** file has a name. By default, there are three connections defined: **sqlite**, **mysql**, **sqlsrv**, and **pgsql**. You are free to change these connection names. The default connection can be specified via the **default** option:
'default' => 'sqlite';
The default connection will always be used by the [fluent query builder](/docs/database/fluent). If you need to change the default connection during a request, use the **Config::set** method.
\ No newline at end of file
This diff is collapsed.
# Fluent Query Builder
## Contents
- [The Basics](#the-basics)
- [Retrieving Records](#get)
- [Building Where Clauses](#where)
- [Nested Where Clauses](#nested-where)
- [Dynamic Where Clauses](#dynamic)
- [Table Joins](#joins)
- [Ordering Results](#ordering)
- [Skip & Take](#limit)
- [Aggregates](#aggregates)
- [Expressions](#expressions)
- [Inserting Records](#insert)
- [Updating Records](#update)
- [Deleting Records](#delete)
## The Basics
The Fluent Query Builder is Laravel's powerful fluent interface for building SQL queries and working with your database. All queries use prepared statements and are protected against SQL injection.
You can begin a fluent query using the **table** method on the DB class. Just mention the table you wish to query:
$query = DB::table('users');
You now have a fluent query builder for the "users" table. Using this query builder, you can retrieve, insert, update, or delete records from the table.
<a name="get"></a>
## Retrieving Records
#### Retrieving an array of records from the database:
$users = DB::table('users')->get();
> **Note:** The **get** method returns an array of objects with properties corresponding to the column on the table.
#### Retrieving a single record from the database:
$user = DB::table('users')->first();
#### Retrieving a single record by its primary key:
$user = DB::table('users')->find($id);
> **Note:** If no results are found, the **first** method will return NULL. The **get** method will return an empty array.
#### Retrieving the value of a single column from the database:
$email = DB::table('users')->where('id', '=', 1)->only('email');
#### Only selecting certain columns from the database:
$user = DB::table('users')->get(array('id', 'email as user_email'));
#### Selecting distinct results from the database:
$user = DB::table('users')->distinct()->get();
<a name="where"></a>
## Building Where Clauses
### where and or\_where
There are a variety of methods to assist you in building where clauses. The most basic of these methods are the **where** and **or_where** methods. Here is how to use them:
return DB::table('users')
->where('id', '=', 1)
->or_where('email', '=', 'example@gmail.com')
->first();
Of course, you are not limited to simply checking equality. You may also use **greater-than**, **less-than**, **not-equal**, and **like**:
return DB::table('users')
->where('id', '>', 1)
->or_where('name', 'LIKE', '%Taylor%')
->first();
As you may have assumed, the **where** method will add to the query using an AND condition, while the **or_where** method will use an OR condition.
### where\_in, where\_not\_in, or\_where\_in, and or\_where\_not\_in
The suite of **where_in** methods allows you to easily construct queries that search an array of values:
DB::table('users')->where_in('id', array(1, 2, 3))->get();
DB::table('users')->where_not_in('id', array(1, 2, 3))->get();
DB::table('users')
->where('email', '=', 'example@gmail.com')
->or_where_in('id', array(1, 2, 3))
->get();
DB::table('users')
->where('email', '=', 'example@gmail.com')
->or_where_not_in('id', array(1, 2, 3))
->get();
### where\_null, where\_not\_null, or\_where\_null, and or\_where\_not\_null
The suite of **where_null** methods makes checking for NULL values a piece of cake:
return DB::table('users')->where_null('updated_at')->get();
return DB::table('users')->where_not_null('updated_at')->get();
return DB::table('users')
->where('email', '=', 'example@gmail.com')
->or_where_null('updated_at')
->get();
return DB::table('users')
->where('email', '=', 'example@gmail.com')
->or_where_not_null('updated_at')
->get();
<a name="nested-where"></a>
## Nested Where Clauses
You may discover the need to group portions of a WHERE clause within parentheses. Just pass a Closure as parameter to the **where** or **or_where** methods:
$users = DB::table('users')
->where('id', '=', 1)
->or_where(function($query)
{
$query->where('age', '>', 25);
$query->where('votes' '>', 100);
})
->get();
The example above would generate a query that looks like:
SELECT * FROM "users" WHERE "id" = ? OR ("age" > ? AND "votes" > ?)
<a name="dynamic"></a>
## Dynamic Where Clauses
Dynamic where methods are great way to increase the readability of your code. Here are some examples:
$user = DB::table('users')->where_email('example@gmail.com')->first();
$user = DB::table('users')->where_email_and_password('example@gmail.com', 'secret');
$user = DB::table('users')->where_id_or_name(1, 'Fred');
<a name="joins"></a>
## Table Joins
Need to join to another table? Try the **join** and **left\_join** methods:
DB::table('users')
->join('phone', 'users.id', '=', 'phone.user_id')
->get(array('users.email', 'phone.number'));
The **table** you wish to join is passed as the first parameter. The remaining three parameters are used to construct the **ON** clause of the join.
Once you know how to use the join method, you know how to **left_join**. The method signatures are the same:
DB::table('users')
->left_join('phone', 'users.id', '=', 'phone.user_id')
->get(array('users.email', 'phone.number'));
You may also specify multiple conditions for an **ON** clause by passing a Closure as the second parameter of the join:
DB::table('users')
->join('phone', function($join)
{
$join->on('users.id', '=', 'phone.user_id');
$join->or_on('users.id', '=', 'phone.contact_id');
})
->get(array('users.email', 'phone.numer'));
<a name="ordering"></a>
## Ordering Results
You can easily order the results of your query using the **order_by** method. Simply mention the column and direction (desc or asc) of the sort:
return DB::table('users')->order_by('email', 'desc')->get();
Of course, you may sort on as many columns as you wish:
return DB::table('users')
->order_by('email', 'desc')
->order_by('name', 'asc')
->get();
<a name="limit"></a>
## Skip & Take
If you would like to **LIMIT** the number of results returned by your query, you can use the **take** method:
return DB::table('users')->take(10)->get();
To set the **OFFSET** of your query, use the **skip** method:
return DB::table('users')->skip(10)->get();
<a name="aggregates"></a>
## Aggregates
Need to get a **MIN**, **MAX**, **AVG**, **SUM**, or **COUNT** value? Just pass the column to the query:
$min = DB::table('users')->min('age');
$max = DB::table('users')->max('weight');
$avg = DB::table('users')->avg('salary');
$sum = DB::table('users')->sum('votes');
$count = DB::table('users')->count();
Of course, you may wish to limit the query using a WHERE clause first:
$count = DB::table('users')->where('id', '>', 10)->count();
<a name="expressions"></a>
## Expressions
Sometimes you may need to set the value of a column to a SQL function such as **NOW()**. Usually a reference to now() would automatically be quoted and escaped. To prevent this use the **raw** method on the **DB** class. Here's what it looks like:
DB::table('users')->update(array('updated_at' => DB::raw('NOW()')));
The **raw** method tells the query to inject the contents of the expression into the query as a string rather than a bound parameter. For example, you can also use expressions to increment column values:
DB::table('users')->update(array('votes' => DB::raw('votes + 1')));
Of course, convenient methods are provided for **increment** and **decrement**:
DB::table('users')->increment('votes');
DB::table('users')->decrement('votes');
<a name="insert"></a>
## Inserting Records
The insert method expects an array of values to insert. The insert method will return true or false, indicating whether the query was successful:
DB::table('users')->insert(array('email' => 'example@gmail.com'));
Inserting a record that has an auto-incrementing ID? You can use the **insert\_get\_id** method to insert a record and retrieve the ID:
$id = DB::table('users')->insert_get_id(array('email' => 'example@gmail.com'));
> **Note:** The **insert\_get\_id** method expects the name of the auto-incrementing column to be "id".
<a name="update"></a>
## Updating Records
To update records simply pass an array of values to the **update** method:
$affected = DB::table('users')->update(array('email' => 'new_email@gmail.com'));
Of course, when you only want to update a few records, you should add a WHERE clause before calling the update method:
$affected = DB::table('users')
->where('id', '=', 1)
->update(array('email' => 'new_email@gmail.com'));
<a name="delete"></a>
## Deleting Records
When you want to delete records from your database, simply call the **delete** method:
$affected = DB::table('users')->where('id', '=', 1)->delete();
Want to quickly delete a record by its ID? No problem. Just pass the ID into the delete method:
$affected = DB::table('users')->delete(1);
\ No newline at end of file
# Migrations
## Contents
- [The Basics](#the-basics)
- [Prepping Your Database](#prepping-your-database)
- [Creating Migrations](#creating-migrations)
- [Running Migrations](#running-migrations)
- [Rolling Back](#rolling-back)
<a name="the-basics"></a>
## The Basics
Think of migrations as a type of version control for your database. Let's say your working on a team, and you all have local databases for development. Good ole' Eric makes a change to the database and checks in his code that uses the new column. You pull in the code, and your application breaks because you don't have the new column. What do you do? Migrations are the answer. Let's dig in deeper to find out how to use them!
<a name="prepping-your-database"></a>
## Prepping Your Database
Before you can run migrations, we need to do some work on your database. Laravel uses a special table to keep track of which migrations have already run. To create this table, just use the Artisan command-line:
**Creating the Laravel migrations table:**
php artisan migrate:install
<a name="creating-migrations"></a>
## Creating Migrations
You can easily create migrations through Laravel's "Artisan" CLI. It looks like this:
**Creating a migration**
php artisan migrate:make create_users_table
Now, check your **application/migrations** folder. You should see your brand new migration! Notice that it also contains a timestamp. This allows Laravel to run your migrations in the correct order.
You may also create migrations for a bundle.
**Creating a migration for a bundle:**
php artisan migrate:make bundle::create_users_table
*Further Reading:*
- [Schema Builder](/docs/database/schema)
<a name="running-migrations"></a>
## Running Migrations
**Running all outstanding migrations in application and bundles:**
php artisan migrate
**Running all outstanding migrations in the application:**
php artisan migrate application
**Running all outstanding migrations in a bundle:**
php artisan migrate bundle
<a name="rolling-back"></a>
## Rolling Back
When you roll back a migration, Laravel rolls back the entire migration "operation". So, if the last migration command ran 122 migrations, all 122 migrations would be rolled back.
**Rolling back the last migration operation:**
php artisan migrate:rollback
**Roll back all migrations that have ever run:**
php artisan migrate:reset
\ No newline at end of file
# Raw Queries
## Contents
- [The Basics](#the-basics)
- [Other Query Methods](#other-query-methods)
- [PDO Connections](#pdo-connections)
<a name="the-bascis"></a>
## The Basics
The **query** method is used to execute arbitrary, raw SQL against your database connection.
#### Selecting records from the database:
$users = DB::query('select * from users');
#### Selecting records from the database using bindings:
$users = DB::query('select * from users where name = ?', array('test'));
#### Inserting a record into the database
$success = DB::query('insert into users values (?, ?)', $bindings);
#### Updating table records and getting the number of affected rows:
$affected = DB::query('update users set name = ?', $bindings);
#### Deleting from a table and getting the number of affected rows:
$affected = DB::query('delete from users where id = ?', array(1));
<a name="other-query-methods"></a>
## Other Query Methods
Laravel provides a few other methods to make querying your database simple. Here's an overview:
#### Running a SELECT query and returning the first result:
$user = DB::first('select * from users where id = 1');
#### Running a SELECT query and getting the value of a single column:
$email = DB::only('select email from users where id = 1');
<a name="pdo-connections"></a>
## PDO Connections
Sometimes you may wish to access the raw PDO connection behind the Laravel Connection object.
#### Get the raw PDO connection for a database:
$pdo = DB::connection('sqlite')->pdo;
> **Note:** If no connection name is specified, the **default** connection will be returned.
\ No newline at end of file
# Redis
## Contents
- [The Basics](#the-basics)
- [Configuration](#config)
- [Usage](#usage)
<a name="the-basics"></a>
## The Basics
[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="config"></a>
## Configuration
The Redis configuration for your application lives in the **application/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 **db** method on the **Redis** class:
$redis = Redis::db();
This will give you an instance of the **default** Redis server. You may pass the server name to the **db** method to get a specific server as defined in your Redis configuration:
$redis = Redis::db('redis_2');
Great! Now that we 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 comment 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 **run** method:
$values = $redis->run('lrange', array(5, 10));
Just want to execute commands on the default Redis server? You can 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/config#redis) and [session](/docs/session/config#redis) drivers are included with Laravel.
\ No newline at end of file
# Schema Builder
## Contents
- [The Basics](#the-basics)
- [Creating & Dropping Tables](#creating-dropping-tables)
- [Adding Columns](#adding-columns)
- [Dropping Columns](#dropping-columns)
- [Adding Indexes](#adding-indexes)
- [Dropping Indexes](#dropping-indexes)
- [Foreign Keys](#foreign-keys)
<a name="the-basics"></a>
## The Basics
The Schema Bulder provides methods for creating and modifying your database tables. Using a fluent syntax, you can work with your tables without using any vendor specific SQL.
*Further Reading:*
- [Migrations](/docs/database/migrations)
<a name="creating-dropping-tables"></a>
## Creating & Dropping Tables
The **Schema** class is used to create and modify tables. Let's jump right into an example:
#### Creating a simple database table:
Schema::create('users', function($table)
{
$table->increments('id');
});
Let's go over this example. The **create** method tells the Schema builder that this is a new table, so it should be created. In the second argument, we passed a Closure which receives a Table instance. Using this Table object, we can fluently add and drop columns and indexes on the table.
#### Dropping a table from the database:
Schema::drop('users');
Sometimes you may need to specify the database connection on which the schema operation should be performed.
#### Specifying the connection to run the operation on:
Schema::create('users', function($table)
{
$table->on('connection');
});
<a name="adding-columns"></a>
## Adding Columns
The fluent table builder's methods allow you to add columns without using vendor specific SQL. Let's go over it's methods:
Command | Description
------------- | -------------
`$table->increments('id');` | Incrementing ID to the table
`$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->boolean('confirmed');` | BOOLEAN equivalent to the table
`$table->date('created_at');` | DATE 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->blob('data');` | BLOB equivalent to the table
`->nullable()` | Designate that the column allows NULL values
> **Note:** Laravel's "boolean" type maps to a small integer column on all database systems.
#### Example of creating a table and adding columns
Schema::table('users', function($table)
{
$table->create();
$table->increments('id');
$table->string('username');
$table->string('email');
$table->string('phone')->nullable();
$table->text('about');
$table->timestamps();
});
<a name="dropping-columns"></a>
## Dropping Columns
#### Dropping a column from a database table:
$table->drop_column('name');
#### Dropping several columns from a database table:
$table->drop_column(array('name', 'email'));
<a name="adding-indexes"></a>
## Adding Indexes
The Schema builder supports several types of indexes. There are two ways to add the indexes. Each type of index has its method; however, you can also fluently define an index on the same line as a column addition. Let's take a look:
#### Fluently creating a string column with an index:
$table->string('email')->unique();
If defining the indexes on a separate line is more your style, here are example of using each of the index methods:
Command | Description
------------- | -------------
`$table->primary('id');` | Adding a primary key
`$table->primary(array('fname', 'lname'));` | Adding composite keys
`$table->unique('email');` | Adding a unique index
`$table->fulltext('description');` | Adding a full-text index
`$table->index('state');` | Adding a basic index
<a name="dropping-indexes"></a>
## Dropping Indexes
To drop indexes you must specify the index's name. Laravel assigns a reasonable name to all indexes. Simply concatenate the table name and the names of the columns in the index, then append the type of the index. Let's take a look at some examples:
Command | Description
------------- | -------------
`$table->drop_primary('users_id_primary');` | Dropping a primary key from the "users" table
`$table->drop_unique('users_email_unique');` | Dropping a unique index from the "users" table
`$table->drop_fulltext('profile_description_fulltext');` | Dropping a full-text index from the "profile" table
`$table->drop_index('geo_state_index');` | Dropping a basic index from the "geo" table
<a name="foreign-keys"></a>
## Foreign Keys
You may easily add foreign key constraints to your table using Schema's fluent interface. For example, let's assume you have a **user_id** on a **posts** table, which references the **id** column of the **users** table. Here's how to add a foreign key constraint for the column:
$table->foreign('user_id')->references('id')->on('users');
You may also specify options for the "on delete" and "on update" actions of the foreign key:
$table->foreign('user_id')->references('id')->on('users')->on_delete('restrict');
$table->foreign('user_id')->references('id')->on('users')->on_update('cascade');
You may also easily drop a foreign key constraint. The default foreign key names follow the [same convention](#dropping-indexes) as the other indexes created by the Schema builder. Here's an example:
$table->drop_foreign('posts_user_id_foreign');
\ No newline at end of file
# Encryption
## Contents
- [The Basics](#the-basics)
- [Encrypting A String](#encrypt)
- [Decrypting A String](#decrypt)
<a name="the-basics"></a>
## The Basics
Laravel's **Crypter** class provides a simple interface for handling secure, two-way encryption. By default, the Crypter class provides strong AES-256 encryption and decryption out of the box via the Mcrypt PHP extension.
> **Note:** Don't forget to install the Mcrypt PHP extension on your server.
<a name="encrypt"></a>
## Encrypting A String
#### Encrypting a given string:
$encrypted = Crypter::encrypt($value);
<a name="decrypt"></a>
## Decrypting A String
#### Decrypting a string:
$decrypted = Crypter::decrypt($encrypted);
> **Note:** It's incredibly important to point out that the decrypt method will only decrypt strings that were encrypted using **your** application key.
\ No newline at end of file
# Events
## Contents
- [The Basics](#the-basics)
- [Firing Events](#firing-events)
- [Listening To Events](#listening-to-events)
- [Laravel Events](#laravel-events)
<a name="the-basics"></a>
## The Basics
Events can provide a great away to build de-coupled applications, and allow plug-ins to tap into the core of your application without modifying its code.
<a name="firing-events"></a>
## Firing Events
To fire an event, just tell the **Event** class the name of the event you want to fire:
#### Firing an event:
$responses = Event::fire('loaded');
Notice that we assigned the result of the **fire** method to a variable. This method will return an array containing the responses of all the event's listeners.
Sometimes you may want to fire an event, but just get the first response. Here's how:
#### Firing an event and retrieving the first response:
$response = Event::first('loaded');
> **Note:** The **first** method will still fire all of the handlers listening to the event, but will only return the first response.
The **Event::until** method will execute the event handlers until the first non-null response is returned.
#### Firing an event until the first non-null response:
$response = Event::until('loaded');
<a name="listening-to-events"></a>
## Listening To Events
So, what good are events if nobody is listening? Register an event handler that will be called when an event fires:
#### Registering an event handler:
Event::listen('loaded', function()
{
// I'm executed on the "loaded" event!
});
The Closure we provided to the method will be executed each time the "loaded" event is fired.
<a name="laravel-events"></a>
## Laravel Events
There are several events that are fired by the Laravel core. Here they are:
#### Event fired when a bundle is started:
Event::listen('laravel.started: bundle', function() {});
#### Event fired when a database query is executed:
Event::listen('laravel.query', function($sql, $bindings, $time) {});
#### Event fired right before response is sent to browser:
Event::listen('laravel.done', function($response) {});
#### Event fired when a messaged is logged using the Log class:
Event::listen('laravel.log', function($type, $message) {});
\ No newline at end of file
# Working With Files
## Contents
- [Reading Files](#get)
- [Writing Files](#put)
- [File Uploads](#upload)
- [File Extensions](#ext)
- [Checking File Types](#is)
- [Getting MIME Types](#mime)
- [Copying Directories](#cpdir)
- [Removing Directories](#rmdir)
<a name="get"></a>
## Reading Files
#### Getting the contents of a file:
$contents = File::get('path/to/file');
<a name="put"></a>
## Writing Files
#### Writing to a file:
File::put('path/to/file', 'file contents');
#### Appending to a file:
File::append('path/to/file', 'appended file content');
<a name="upload"></a>
## File Uploads
#### Moving a $_FILE to a permanent location:
Input::upload('picture', 'path/to/pictures');
> **Note:** You can easily validate file uploads using the [Validator class](/docs/validation).
<a name="ext"></a>
## File Extensions
#### Getting the extension from a filename:
File::extension('picture.png');
<a name="is"></a>
## Checking File Types
#### Determining if a file is given type:
if (File::is('jpg', 'path/to/file.jpg'))
{
//
}
The **is** method does not simply check the file extension. The Fileinfo PHP extension will be used to read the content of the file and determine the actual MIME type.
> **Note:** You may pass any of the extensions defined in the **application/config/mimes.php** file to the **is** method.
> **Note:** The Fileinfo PHP extension is required for this functionality. More information can be found on the [PHP Fileinfo page](http://php.net/manual/en/book.fileinfo.php).
<a name="mime"></a>
## Getting MIME Types
#### Getting the MIME type associated with an extension:
echo File::mime('gif');
> **Note:** This method simply returns the MIME type defined for the extension in the **application/config/mimes.php** file.
<a name="cpdir"></a>
## Copying Directories
#### Recursively copy a directory to a given location:
File::cpdir($directory, $destination);
<a name="rmdir"></a>
## Removing Directories
#### Recursively delete a directory:
File::rmdir($directory);
\ No newline at end of file
# Laravel Documentation
- [The Basics](#the-basics)
- [Who Will Enjoy Laravel?](#who-will-enjoy-laravel)
- [What Makes Laravel Different?](#laravel-is-different)
- [Application Structure](#application-structure)
- [Laravel's Community](#laravel-community)
- [License Information](#laravel-license)
<a name="the-basics"></a>
## The Basics
Welcome to the Laravel documentation. These documents were designed to function both as a getting-started guide and as a feature reference. Even though you may jump into any section and start learning, we recommend reading the documentation in order as it allows us to progressively establish concepts that will be used in later documents.
<a name="who-will-enjoy-laravel"></a>
## Who Will Enjoy Laravel?
Laravel is a powerful framework that emphasizes flexibility and expressiveness. Users new to Laravel will enjoy the same ease of development that is found in the most popular and lightweight PHP frameworks. More experienced users will appreciate the opportunity to modularize their code in ways that are not possible with other frameworks. Laravel's flexibility will allow your organization to update and mold the application over time as is needed and its expressiveness will allow you and your team to develop code that is both concise and easily read.
<a name="laravel-is-different"></a>
## What Makes Laravel Different?
There are many ways in which Laravel differentiates itself from other frameworks. Here are a few examples that we think make good bullet points:
- **Bundles** are Laravel's modular packaging system. [The Laravel Bundle Repository](http://bundles.laravel.com/) is already populated with quite a few features that can be easily added to your application. You can either download a bundle repository to your bundles directory or use the "Artisan" command-line tool to automatically install them.
- **The Eloquent ORM** is the most advanced PHP ActiveRecord implementation available. With the capacity to easily apply constraints to both relationships and nested eager-loading you'll have complete control over your data with all of the conveniences of ActiveRecord. Eloquent natively supports all of the methods from Laravel's Fluent query-builder.
- **Application Logic** can be implemented within your application either using controllers (which many web-developers are already familiar with) or directly into route declarations using syntax similar to the Sinatra framework. Laravel is designed with the philosophy of giving a developer the flexibility that they need to create everything from very small sites to massive enterprise applications.
- **Reverse Routing** allows you to create links to named routes. When creating links just use the route's name and Laravel will automatically insert the correct URI. This allows you to change your routes at a later time and Laravel will update all of the relevant links site-wide.
- **Restful Controllers** are an optional way to separate your GET and POST request logic. In a login example your controller's get_login() action would serve up the form and your controller's post_login() action would accept the posted form, validate, and either redirect to the login form with an error message or redirect your user to their dashboard.
- **Class Auto Loading** keeps you from having to maintain an autoloader configuration and from loading unnecessary components when they won't be used. Want to use a library or model? Don't bother loading it, just use it. Laravel will handle the rest.
- **View Composers** are blocks of code that can be run when a view is loaded. A good example of this would be a blog side-navigation view that contains a list of random blog posts. Your composer would contain the logic to load the blog posts so that all you have to do i load the view and it's all ready for you. This keeps you from having to make sure that your controllers load the a bunch of data from your models for views that are unrelated to that method's page content.
- **The IoC container** (Inversion of Control) gives you a method for generating new objects and optionally instantiating and referencing singletons. IoC means that you'll rarely ever need to bootstrap any external libraries. It also means that you can access these objects from anywhere in your code without needing to deal with an inflexible monolithic structure.
- **Migrations** are version control for your database schemas and they are directly integrated into Laravel. You can both generate and run migrations using the "Artisan" command-line utility. Once another member makes schema changes you can update your local copy from the repository and run migrations. Now you're up to date, too!
- **Unit-Testing** is an important part of Laravel. Laravel itself sports hundreds of tests to help ensure that new changes don't unexpectedly break anything. This is one of the reasons why Laravel is widely considered to have some of the most stable releases in the industry. Laravel also makes it easy for you to write unit-tests for your own code. You can then run tests with the "Artisan" command-line utility.
- **Automatic Pagination** prevents your application logic from being cluttered up with a bunch of pagination configuration. Instead of pulling in the current page, getting a count of db records, and selected your data using a limit/offset just call 'paginate' and tell Laravel where to output the paging links in your view. Laravel automatically does the rest. Laravel's pagination system was designed to be easy to implement and easy to change. It's also important to note that just because Laravel can handle these things automatically doesn't mean that you can't call and configure these systems manually if you prefer.
These are just a few ways in which Laravel differentiates itself from other PHP frameworks. All of these features and many more are discussed thoroughly in this documentation.
<a name="application-structure"></a>
## Application Structure
Laravel's directory structure is designed to be familiar to users of other popular PHP frameworks. Web applications of any shape or size can easily be created using this structure similarly to the way that they would be created in other frameworks.
However due to Laravel's unique architecture, it is possible for developers to create their own infrastructure that is specifically designed for their application. This may be most beneficial to large projects such as content-management-systems. This kind of architectural flexibility is unique to Laravel.
Throughout the documentation we'll specify the default locations for declarations where appropriate.
<a name="laravel-community"></a>
## Laravel's Community
Laravel is lucky to be supported by rapidly growing, friendly and enthusiastic community. The [Laravel Forums](http://forums.laravel.com) are a great place to find help, make a suggestion, or just see what other people are saying.
Many of us hang out every day in the #laravel IRC channel on FreeNode. [Here's a forum post explaining how you can join us.](http://forums.laravel.com/viewtopic.php?id=671) Hanging out in the IRC channel is a really great way to learn more about web-development using Laravel. You're welcome to ask questions, answer other people's questions, or just hang out and learn from other people's questions being answered. We love Laravel and would love to talk to you about it, so don't be a stranger!
<a name="laravel-license"></a>
## License Information
Laravel is open-sourced software licensed under the [MIT License](http://www.opensource.org/licenses/mit-license.php).
\ No newline at end of file
# Input & Cookies
## Contents
- [Input](#input)
- [Files](#files)
- [Old Input](#old-input)
- [Redirecting With Old Input](#redirecting-with-old-input)
- [Cookies](#cookies)
<a name="input"></a>
## Input
The **Input** class handles input that comes into your application via GET, POST, PUT, or DELETE requests. Here are some examples of how to access input data using the Input class:
#### Retrieve a value from the input array:
$email = Input::get('email');
> **Note:** The "get" method is used for all request types (GET, POST, PUT, and DELETE), not just GET requests.
#### Retrieve all input from the input array:
$input = Input::get();
#### Retrieve all input including the $_FILES array:
$input = Input::all();
By default, *null* will be returned if the input item does not exist. However, you may pass a different default value as a second parameter to the method:
#### Returning a default value if the requested input item doesn't exist:
$name = Input::get('name', 'Fred');
#### Using a Closure to return a default value:
$name = Input::get('name', function() {return 'Fred';});
#### Determining if the input contains a given item:
if (Input::has('name')) ...
> **Note:** The "has" method will return *false* if the input item is an empty string.
<a name="files"></a>
## Files
#### Retrieving all items from the $_FILES array:
$files = Input::file();
#### Retrieving an item from the $_FILES array:
$picture = Input::file('picture');
#### Retrieving a specific item from a $_FILES array:
$size = Input::file('picture.size');
<a name="old-input"></a>
## Old Input
You'll commonly need to re-populate forms after invalid form submissions. Laravel's Input class was designed with this problem in mind. Here's an example of how you can easily retrieve the input from the previous request. First, you need to flash the input data to the session:
#### Flashing input to the session:
Input::flash();
#### Flashing selected input to the session:
Input::flash('only', array('username', 'email'));
Input::flash('except', array('password', 'credit_card'));
#### Retrieving a flashed input item from the previous request:
$name = Input::old('name');
> **Note:** You must specify a session driver before using the "old" method.
*Further Reading:*
- *[Sessions](/docs/session/config)*
<a name="redirecting-with-old-input"></a>
## Redirecting With Old Input
Now that you know how to flash input to the session. Here's a shortcut that you can use when redirecting that prevents you from having to micro-manage your old input in that way:
#### Flashing input from a Redirect instance:
return Redirect::to('login')->with_input();
#### Flashing selected input from a Redirect instance:
return Redirect::to('login')->with_input('only', array('username'));
return Redirect::to('login')->with_input('except', array('password'));
<a name="cookies"></a>
## Cookies
Laravel provides a nice wrapper around the $_COOKIE array. However, there are a few things you should be aware of before using it. First, all Laravel cookies contain a "signature hash". This allows the framework to verify that the cookie has not been modified on the client. Secondly, when setting cookies, the cookies are not immediately sent to the browser, but are pooled until the end of the request and then sent together. This means that you will not be able to both set a cookie and retrieve the value that you set in the same request.
#### Retrieving a cookie value:
$name = Cookie::get('name');
#### Returning a default value if the requested cookie doesn't exist:
$name = Cookie::get('name', 'Fred');
#### Setting a cookie that lasts for 60 minutes:
Cookie::put('name', 'Fred', 60);
#### Creating a "permanent" cookie that lasts five years:
Cookie::forever('name', 'Fred');
#### Deleting a cookie:
Cookie::forget('name');
\ No newline at end of file
# Installation & Setup
## Contents
- [Requirements](#requirements)
- [Installation](#installation)
- [Basic Configuration](#basic-configuration)
- [Environments](#environments)
- [Cleaner URLs](#cleaner-urls)
<a name="requirements"></a>
## Requirements
- Apache, nginx, or another compatible web server.
- Laravel takes advantage of the powerful features that have become available in PHP 5.3. Consequently, PHP 5.3 is a requirement.
- Laravel uses the [FileInfo library](http://php.net/manual/en/book.fileinfo.php) to detect files' mime-types. This is included by default with PHP 5.3. However, Windows users may need to add a line to their php.ini file before the Fileinfo module is enabled. For more information check out the [installation / configuration details on PHP.net](http://php.net/manual/en/fileinfo.installation.php).
- Laravel uses the [Mcrypt library](http://php.net/manual/en/book.mcrypt.php) for encryption and hash generation. Mcrypt typically comes pre-installed. If you can't find Mcrypt in the output of phpinfo() then check the vendor site of your LAMP installation or check out the [installation / configuration details on PHP.net](http://php.net/manual/en/book.mcrypt.php).
<a name="installation"></a>
## Installation
1. [Download Laravel](http://laravel.com/download)
2. Extract the Laravel archive and upload the contents to your web server.
3. Set the value of the **key** option in the **config/application.php** file to a random, 32 character string.
4. Navigate to your application in a web browser.
If all is well, you should see a pretty Laravel splash page. Get ready, there is lots more to learn!
### Extra Goodies
Installing the following goodies will help you take full advantage of Laravel, but they are not required:
- SQLite, MySQL, PostgreSQL, or SQL Server PDO drivers.
- Memcached or APC.
### Problems?
If you are having problems installing, try the following:
- Make sure the **public** directory is the document root of your web server.
- If you are using mod_rewrite, set the **index** option in **application/config/application.php** to an empty string.
<a name="basic-configuration"></a>
## Basic Configuration
All of the configuration provided are located in your applications config/ directory. We recommend that you read through these files just to get a basic understanding of the options available to you. Pay special attention to the **application/config/application.php** file as it contains the basic configuration options for your application.
It's **extremely** important that you change the **application key** option before working on your site. This key is used throughout the framework for encryption, hashing, etc. It lives in the **config/application.php** file and should be set to a random, 32 character string. A standards-compliant application key can be automatically generated using the Artisan command-line utility. More information can be found in the [Artisan command index](/docs/artisan/commands).
> **Note:** If you are using mod_rewrite, you should set the index option to an empty string.
<a name="environments"></a>
## Environments
Most likely, the configuration options you need for local development are not the same as the options you need on your production server. Laravel's default environment handling mechanism is the **LARAVEL_ENV** environment variable. To get started, set the environment variable in your **httpd.conf** file:
SetEnv LARAVEL_ENV local
> **Note:** Using a web server other than Apache? Check your server's documentation to learn how to set environment variables.
Next, create an **application/config/local** directory. Any files and options you place in this directory will override the options in the base **application/config** directory. For example, you may wish to create an **application.php** file within your new **local** configuration directory:
return array(
'url' => 'http://localhost/laravel/public',
);
In this example, the local **URL** option will override the **URL** option in **application/config/application.php**. Notice that you only need to specify the options you wish to override.
If you do not have access to your server's configuration files, you may manually set the **LARAVEL_ENV** variable at the top of Laravel's **paths.php** file:
$_SERVER['LARAVEL_ENV'] = 'local';
<a name="cleaner-urls"></a>
## Cleaner URLs
Most likely, you do not want your application URLs to contain "index.php". You can remove it using HTTP rewrite rules. If you are using Apache to serve your application, make sure to enable mod_rewrite and create a **.htaccess** file like this one in your **public** directory:
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]
</IfModule>
Is the .htaccess file above not working for you? Try this one:
Options +FollowSymLinks
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . index.php [L]
After setting up HTTP rewriting, you should set the **index** configuration option in **application/config/application.php** to an empty string.
> **Note:** Each web server has a different method of doing HTTP rewrites, and may require a slightly different .htaccess file.
\ No newline at end of file
# IoC Container
- [Definition](/docs/ioc#definition)
- [Registering Objects](/docs/ioc#register)
- [Resolving Objects](/docs/ioc#resolve)
<a name="definition"></a>
## Definition
An IoC container is simply a way of managing the creation of objects. You can use it to define the creation of complex objects, allowing you to resolve them throughout your application using a single line of code. You may also use it to "inject" dependencies into your classes and controllers.
IoC containers help make your application more flexible and testable. Since you may register alternate implementations of an interface with the container, you may isolate the code you are testing from external dependencies using [stubs and mocks](http://martinfowler.com/articles/mocksArentStubs.html).
<a name="register"></a>
## Registering Objects
#### Registering a resolver in the IoC container:
IoC::register('mailer', function()
{
$transport = Swift_MailTransport::newInstance();
return Swift_Mailer::newInstance($transport);
});
Great! Now we have registered a resolver for SwiftMailer in our container. But, what if we don't want the container to create a new mailer instance every time we need one? Maybe we just want the container to return the same instance after the intial instance is created. Just tell the container the object should be a singleton:
#### Registering a singleton in the container:
IoC::singleton('mailer', function()
{
//
});
You may also register an existing object instance as a singleton in the container.
#### Registering an existing instance in the container:
IoC::instance('mailer', $instance);
<a name="resolve"></a>
## Resolving Objects
Now that we have SwiftMailer registered in the container, we can resolve it using the **resolve** method on the **IoC** class:
$mailer = IoC::resolve('mailer');
> **Note:** You may also [register controllers in the container](/docs/controllers#dependency-injection).
\ No newline at end of file
# Class Auto Loading
## Contents
- [The Basics](#the-basics)
- [Registering Directories](#directories)
- [Registering Mappings](#mappings)
- [Registering Namespaces](#namespaces)
<a name="the-basics"></a>
## The Basics
Auto-loading allows you to lazily load class files when they are needed without explicitly *requiring* or *including* them. So, only the classes you actually need are loaded for any given request to your application, and you can just jump right in and start using any class without loading it's related file.
By default, the **models** and **libraries** directories are registered with the auto-loader in the **application/start.php** file. The loader uses a class to file name loading convention, where all file names are lower-cased. So for instance, a "User" class within the models directory should have a file name of "user.php". You may also nest classes within sub-directories. Just namespace the classes to match the directory structure. So, a "Entities\User" class would have a file name of "entities/user.php" within the models directory.
<a name="directories"></a>
## Registering Directories
As noted above, the models and libraries directories are registered with the auto-loader by default; however, you may register any directories you like to use the same class to file name loading conventions:
#### Registering directories with the auto-loader:
Autoloader::directories(array(
path('app').'entities',
path('app').'repositories',
));
<a name="mappings"></a>
## Registering Mappings
Sometimes you may wish to manually map a class to its related file. This is the most performant way of loading classes:
#### Registering a class to file mapping with the auto-loader:
Autoloader::map(array(
'User' => path('app').'models/user.php',
'Contact' => path('app').'models/contact.php',
));
<a name="namespaces"></a>
## Registering Namespaces
Many third-party libraries use the PSR-0 standard for their structure. PSR-0 states that class names should match their file names, and directory structure is indicated by namespaces. If you are using a PSR-0 library, just register it's root namespace and directory with the auto-loader:
#### Registering a namespace with the auto-loader:
Autoloader::namespaces(array(
'Doctrine' => path('libraries').'Doctrine',
));
Before namespaces were available in PHP, many projects used underscores to indicate directory structure. If you are using one of these legacy libraries, you can still easily register it with the auto-loader. For example, if you are using SwiftMailer, you may have noticed all classes begin with "Swift_". So, we'll register "Swift" with the auto-loader as the root of an underscored project.
#### Registering an "underscored" library with the auto-loader:
Autoloader::underscored(array(
'Swift' => path('libraries').'SwiftMailer',
));
\ No newline at end of file
# Localization
## Contents
- [The Basics](#the-basics)
- [Retrieving A Language Line](#get)
- [Place Holders & Replacements](#replace)
<a name="the-basics"></a>
## The Basics
Localization is the process of translating your application into different languages. The **Lang** class provides a simple mechanism to help you organize and retrieve the text of your multilingual application.
All of the language files for your application live under the **application/language** directory. Within the **application/language** directory, you should create a directory for each language your application speaks. So, for example, if your application speaks English and Spanish, you might create **en** and **sp** directories under the **language** directory.
Each language directory may contain many different language files. Each language file is simply an array of string values in that language. In fact, language files are structured identically to configuration files. For example, within the **application/language/en** directory, you could create a **marketing.php** file that looks like this:
#### Creating a language file:
return array(
'welcome' => 'Welcome to our website!',
);
Next, you should create a corresponding **marketing.php** file within the **application/language/sp** directory. The file would look something like this:
return array(
'welcome' => 'Bienvenido a nuestro sitio web!',
);
Nice! Now you know how to get started setting up your language files and directories. Let's keep localizing!
<a name="basics"></a>
## Retrieving A Language Line
#### Retrieving a language line:
echo Lang::line('marketing.welcome')->get();
#### Retrieving a language line using the "__" helper:
echo __('marketing.welcome');
Notice how a dot was used to separate "marketing" and "welcome"? The text before the dot corresponds to the language file, while the text after the dot corresponds to a specific string within that file.
Need to retrieve the line in a language other than your default? Not a problem. Just mention the language to the **get** method:
#### Getting a language line in a given language:
echo Lang::line('marketing.welcome')->get('sp');
<a name="replace"></a>
## Place Holders & Replacements
Now, let's work on our welcome message. "Welcome to our website!" is a pretty generic message. It would be helpful to be able to specify the name of the person we are welcoming. But, creating a language line for each user of our application would be time-consuming and ridiculous. Thankfully, you don't have to. You can specify "place-holders" within your language lines. Place-holders are preceeded by a colon:
#### Creating a language line with place-holders:
'welcome' => 'Welcome to our website, :name!'
#### Retrieving a language line with replacements:
echo Lang::line('marketing.welcome', array('name' => 'Taylor'))->get();
#### Retrieving a language line with replacements using "__":
echo __('marketing.welcome', array('name' => 'Taylor'));
\ No newline at end of file
# Errors & Logging
## Contents
- [Basic Configuration](#basic-configuration)
- [Logging](#logging)
- [The Logger Class](#the-logger-class)
<a name="basic-configuration"></a>
## Basic Configuration
All of the configuration options regarding errors and logging live in the **application/config/errors.php** file. Let's jump right in.
### Ignored Errors
The **ignore** option contains an array of error levels that should be ignored by Laravel. By "ignored", we mean that we won't stop execution of the script on these errors. However, they will be logged when logging is enabled.
### Error Detail
The **detail** option indicates if the framework should display the error message and stack trace when an error occurs. For development, you will want this to be **true**. However, in a production environment, set this to **false**. When disabled, the view located in **application/views/error/500.php** will be displayed, which contains a generic error message.
<a name="logging"></a>
## Logging
To enable logging, set the **log** option in the error configuration to "true". When enabled, the Closure defined by the **logger** configuration item will be executed when an error occurs. This gives you total flexibility in how the error should be logged. You can even e-mail the errors to your development team!
By default, logs are stored in the **storage/logs** direcetory, and a new log file is created for each day. This keeps your log files from getting crowded with too many messages.
<a name="the-logger-class"></a>
## The Logger Class
Sometimes you may wish to use Laravel's **Log** class for debugging, or just to log informational messages. Here's how to use it:
#### Writing a message to the logs:
Log::write('info', 'This is just an informational message!');
#### Using magic methods to specify the log message type:
Log::info('This is just an informational message!');
\ No newline at end of file
# Models & Libraries
## Contents
- [Models](#models)
- [Libraries](#libraries)
- [Auto-Loading](#auto-loading)
- [Best Practices](#best-practices)
<a name="models"></a>
## Models
Models are the heart of your application. Your application logic (controllers / routes) and views (html) are just the mediums with which users interact with your models. The most typical type of logic contained within a model is [Business Logic](http://en.wikipedia.org/wiki/Business_logic).
*Some examples of functionality that would exist within a model are:*
- Database Interactions
- File I/O
- Interactions with Web Services
For instance, perhaps you are writing a blog. You will likely want to have a "Post" model. Users may want to comment on posts so you'd also have a "Comment" model. If users are going to be commenting then we'll also need a "User" model. Get the idea?
<a name="libraries"></a>
## Libraries
Libraries are classes that perform tasks that aren't specific to your application. For instance, consider a PDF generation library that converts HTML. That task, although complicated, is not specific to your application, so it is considered a "library".
Creating a library is as easy as creating a class and storing it in the libraries folder. In the following example, we will create a simple library with a method that echos the text that is passed to it. We create the **printer.php** file in the libraries folder with the following code.
<?php
class Printer {
public static function write($text) {
echo $text;
}
}
You can now call Printer::write('this text is being echod from the write method!') from anywhere within your application.
<a name="auto-loading"></a>
## Auto Loading
Libraries and Models are very easy to use thanks to the Laravel auto-loader. To learn more about the auto-loader check out the documentation on [Auto-Loading](/docs/loading).
<a name="best-practices"></a>
## Best Practices
We've all head the mantra: "controllers should be thin!" But, how do we apply that in real life? It's possible that part of the problem is the word "model". What does it even mean? Is it even a useful term? Many associate "model" with "database", which leads to having very bloated controllers, with light models that access the database. Let's explore some alternatives.
What if we just totally scrapped the "models" directory? Let's name it something more useful. In fact, let's just give it the same as our application. Perhaps are our satellite tracking site is named "Trackler", so let's create a "trackler" directory within the application folder.
Great! Next, let's break our classes into "entities", "services", and "repositories". So, we'll create each of those three directories within our "trackler" folder. Let's explore each one:
### Entities
Think of entities as the data containers of your application. They primarily just contain properties. So, in our application, we may have a "Location" entity which has "latitude" and "longitude" properties. It could look something like this:
<?php namespace Trackler\Entities;
class Location {
public $latitude;
public $longitude;
public function __construct($latitude, $longitude)
{
$this->latitude = $latitude;
$this->longitude = $longitude;
}
}
Looking good. Now that we have an entity, let's explore our other two folders.
### Services
Services contain the *processes* of your application. So, let's keep using our Trackler example. Our application might have a form on which a user may enter their GPS location. However, we need to validate that the coordinates are correctly formatted. We need to *validate* the *location entity*. So, within our "services" directory, we could create a "validators" folder with the following class:
<?php namespace Trackler\Services\Validators;
use Trackler\Entities\Location;
class Location_Validator {
public static function validate(Location $location)
{
// Validate the location instance...
}
}
Great! Now we have a great way to test our validation in isolation from our controllers and routes! So, we've validated the location and we're ready to store it. What do we do now?
### Repositories
Repositories are the data access layer of your application. They are responsible for storing and retrieving the *entities* of your application. So, let's continue using our *location* entity in this example. We need a location repository that can store them. We could store them using any mechanism we want, whether that is a relational database, Redis, or the next storage hotness. Let's look at an example:
<?php namespace Trackler\Repositories;
use Trackler\Entities\Location;
class Location_Repository {
public function save(Location $location, $user_id)
{
// Store the location for the given user ID...
}
}
Now we have a clean separation of concerns between our application's entities, services, and repositories. This means we can inject stub repositories into our services or controllers, and test those pieces of our application in isolation from the database. Also, we can entirely switch data store technologies without affecting our services, entities, or controllers. We've achieved a good *separation of concerns*.
*Further Reading:*
- [IoC Container](/docs/ioc)
\ No newline at end of file
# Examining Requests
## Contents
- [Working With The URI](#working-with-the-uri)
- [Other Request Helpers](#other-request-helpers)
<a name="working-with-the-uri"></a>
## Working With The URI
#### Getting the current URI for the request:
echo URI::current();
#### Getting a specific segment from the URI:
echo URI::segment(1);
#### Returning a default value if the segment doesn't exist:
echo URI::segment(10, 'Foo');
#### Getting the full request URI, including query string:
echo URI::full();
Sometimes you may need to determine if the current URI is a given string, or begins with a given string. Here's an example of how you can use the is() method to accomplish this:
#### Determine if the URI is "home":
if (URI::is('home'))
{
// The current URI is "home"!
}
#### Determine if the current URI begins with "docs/":
if URI::is('docs/*'))
{
// The current URI begins with "docs/"!
}
<a name="other-request-helpers"></a>
## Other Request Helpers
#### Getting the current request method:
echo Request::method();
#### Accessing the $_SERVER global array:
echo Request::server('http_referer');
#### Retrieving the requester's IP address:
echo Request::ip();
#### Determining if the current request is using HTTPS:
if (Request::secure())
{
// This request is over HTTPS!
}
#### Determing if the current request is an AJAX request:
if (Request::ajax())
{
// This request is using AJAX!
}
#### Determining if the current requst is via the Artisan CLI:
if (Request::cli())
{
// This request came from the CLI!
}
\ No newline at end of file
This diff is collapsed.
<a name="config"></a>
# Session Configuration
## Contents
- [The Basics](#the-basics)
- [Cookie Sessions](#cookie)
- [File System Sessions](#file)
- [Database Sessions](#database)
- [Memcached Sessions](#memcached)
- [Redis Sessions](#redis)
- [In-Memory Sessions](#memory)
<a name="the-basics"></a>
## The Basics
The web is a stateless environment. This means that each request to your application is considered unrelated to any previous request. However, **sessions** allow you to store arbitrary data for each visitor to your application. The session data for each visitor is stored on your web server, while a cookie containing a **session ID** is stored on the visitor's machine. This cookie allows your application to "remember" the session for that user and retrieve their session data on subsequent requests to your application.
> **Note:** Before using sessions, make sure an application key has been specified in the **application/config/application.php** file.
Six session drivers are available out of the box:
- Cookie
- File System
- Database
- Memcached
- Redis
- Memory (Arrays)
<a name="cookie"></a>
## Cookie Sessions
Cookie based sessions provide a light-weight and fast mechanism for storing session information. They are also secure. Each cookie is encrypted using strong AES-256 encryption. However, cookies have a four kilobyte storage limit, so you may wish to use another driver if you are storing a lot of data in the session.
To get started using cookie sessions, just set the driver option in the **application/config/session.php** file:
'driver' => 'cookie'
<a name="file"></a>
## File System Sessions
Most likely, your application will work great using file system sessions. However, if your application receives heavy traffic or runs on a server farm, use database or Memcached sessions.
To get started using file system sessions, just set the driver option in the **application/config/session.php** file:
'driver' => 'file'
That's it. You're ready to go!
> **Note:** File system sessions are stored in the **storage/sessions** directory, so make sure it's writeable.
<a name="database"></a>
## Database Sessions
To start using database sessions, you will first need to [configure your database connection](/docs/database/config).
Next, you will need to create a session table. Below are some SQL statements to help you get started. However, you may also use Laravel's "Artisan" command-line to generate the table for you!
### Artisan
php artisan session:table
### SQLite
CREATE TABLE "sessions" (
"id" VARCHAR PRIMARY KEY NOT NULL UNIQUE,
"last_activity" INTEGER NOT NULL,
"data" TEXT NOT NULL
);
### MySQL
CREATE TABLE `sessions` (
`id` VARCHAR(40) NOT NULL,
`last_activity` INT(10) NOT NULL,
`data` TEXT NOT NULL,
PRIMARY KEY (`id`)
);
If you would like to use a different table name, simply change the **table** option in the **application/config/session.php** file:
'table' => 'sessions'
All you need to do now is set the driver in the **application/config/session.php** file:
'driver' => 'database'
<a name="memcached"></a>
## Memcached Sessions
Before using Memcached sessions, you must [configure your Memcached servers](/docs/database/config#memcached).
Just set the driver in the **application/config/session.php** file:
'driver' => 'memcached'
<a name="redis"></a>
## Redis Sessions
Before using Redis sessions, you must [configure your Redis servers](/docs/database/redis#config).
Just set the driver in the **application/config/session.php** file:
'driver' => 'redis'
<a name="memory"></a>
## In-Memory Sessions
The "memory" session driver just uses a simple array to store your session data for the current request. This driver is perfect for unit testing your application since nothing is written to disk. It shouldn't ever be used as a "real" session driver.
\ No newline at end of file
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment