added documentation to main repository.

This commit is contained in:
Taylor Otwell
2011-07-15 19:25:29 -05:00
parent cec583aafe
commit bfaf6950c6
21 changed files with 2392 additions and 0 deletions

View File

@@ -0,0 +1,78 @@
## Basic Configuration
- [Quick Start](#quick)
- [Cleaner URLs](#clean)
- [Errors & Logging](#errors)
<a name="quick"></a>
### Quick Start
When starting a new project, you shouldn't be bombarded with loads of confusing configuration decisions. For that reason, Laravel is intelligently configured out of the box. The **application/config/application.php** file contains the basic configuration options for your application.
There is only one option that **must** be set when starting a new application. Laravel needs to know the URL you will use to access your application. Simply set the url in the **application/config/application.php** file:
'url' => 'http://localhost';
> **Note:** If you are using mod_rewrite, you should set the index option to an empty string.
<a name="clean"></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.
<a name="errors"></a>
### Errors & Logging
- [404 Errors](#error-404)
- [Error Detail](#error-detail)
- [Logging](#error-logging)
<a name="error-404"></a>
#### 404 Errors
When a request is made to your application that cannot be matched to a route, the 404 error view will be sent to the browser. This view lives in **application/views/error/404.php** and you are free to modify it however you wish.
<a name="error-detail"></a>
#### Error Detail
You can easily control the level of error detail via the **detail** option in the **application/config/errors.php** file.
'detail' => true;
When set to **true**, error messages will be detailed with a stack trace and snippet of the relevant file. When set to **false**, the generic error page (**application/views/error/500.php**) will be displayed. Feel free to modify this view.
> **Note:** In a production environment, it is strongly suggested that you turn off error details.
<a name="error-logging"></a>
#### Logging
You may wish to log any errors that occur in your application. Laravel makes it a breeze. You can turn on logging by setting the log option to **true** in the **application/config/errors.php** file:
'log' => true;
You have total control over how your errors are logged via the **logger** function defined in **application/config/error.php**. This function is called every time there is an unhandled error or exception in your application.
As you can see, the default logger implementation writes to the **application/storage/log.txt** file; however, you are free to modify this function however you wish.

View File

@@ -0,0 +1,27 @@
## Requirements & Installation
### Requirements
- Apache, nginx, or another compatible web server.
- PHP 5.3+.
### Installation
1. [Download Laravel](https://github.com/taylorotwell/laravel/zipball/master)
2. Extract the Laravel archive and upload the contents to your web server.
4. Set the URL of your application in the **application/config/application.php** file.
5. 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!
### Extras
Installing the following goodies will help you take full advantage of Laravel, but they are not required:
- SQLite, MySQL, or PostgreSQL PDO drivers.
- [Memcached](http://memcached.org) or APC.
### Problems?
- 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.

View File

@@ -0,0 +1,232 @@
## Interaction
- [Input](/docs/start/interaction#basics)
- [Old Input](/docs/start/interaction#old)
- [Cookies](/docs/start/interaction#cookies)
- [Building Forms](/docs/start/interaction#forms)
All web applications receive input via HTTP requests. The input can be sent to your application via any of the four HTTP verbs: **GET**, **POST**, **PUT**, or **DELETE**. Input can also be sent to your application via cookies, which can store small amounts of information and are stored on the user's computer.
Let's dig into the classes Laravel provides for working with user input!
> **Note:** Laravel doesn't mess with your query strings. Feel free to use them.
<a name="basics"></a>
## Input
The **Input** class handles input that comes into your application via GET, POST, PUT, or DELETE requests. Retrieving input using the Input class is effortless. Just use the **get** method:
$email = Input::get('email');
> **Note:** The get method is used for all request types, not just GET requests. You may use it on POST, PUT, and DELETE requests as well.
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:
$name = Input::get('name', 'Fred');
Now, "Fred" will be returned if the "name" input item does not exist. You may even pass a closure as a default value:
$name = Input::get('name', function() {return 'Fred';});
Need to determine if an input item exists? Use the **has** method:
if (Input::has('name'))
{
$name = Input::get('name');
}
> **Note:** The **has** method will return **false** if the input item exists but is an empty string.
Need to access the **$_FILES** array? It's easy using the **file** method:
$picture = Input::file('picture');
$size = Input::file('picture.size');
Sometimes you may need to merge the input and $_FILES array. Check out the **all** method:
$input = Input::all();
<a name="old"></a>
## Old Input
Have you ever tried to re-populate an input form after an invalid form submission? It can get pretty clunky. Not in Laravel. You can easily retrieve the input from the previous request using the **old** method on the Input class:
$name = Input::old('name');
> **Note:** You must specifiy a session driver before using the **old** Input method.
As you would expect, you may pass a default value in the second parameter to the method:
$name = Input::old('name', 'Fred');
Once again, there is a simple way to determine if an old input item exists using the **had** method:
if (Input::had('name'))
{
$name = Input::old('name');
}
<a name="cookies"></a>
## Cookies
The **Cookie** class provides simple functions for retrieving, setting, and deleting cookies.
To retrieve a cookie value, simply mention its name to the **get** method:
$name = Cookie::get('name');
Of course, just like the Input class, you may pass a default value in the second parameter to the **get** method:
$name = Cookie::get('name', 'Fred');
Also just like the Input class, the Cookie class has a simple method to determine if a cookie exists:
if (Cookie::has('name'))
{
$name = Cookie::get('name');
}
Need to create a cookie? No problem. Check out the **put** method:
Cookie::put('name', 'Fred', 60);
The put method accepts almost the exact same parameters as the PHP setcookie method. However, just pass the number of **minutes** you want the cookie to live as the third parameter. You don't have to worry about any clunky expiration date calculations.
If you need to create a "permanent" cookie, try the **forever** method. It creates a cookie that lives for five years:
Cookie::forever('name', 'Fred');
To delete a cookie, use the **forget** method:
Cookie::forget('name');
<a name="forms"></a>
## Building Forms
- [Opening A Form](#form-open)
- [CSRF Protection](#form-csrf)
- [Labels](#form-labels)
- [Text, Text Area, Password & Hidden Fields](#form-text)
- [Checkboxes & Radio Buttons](#form-check)
- [Drop-Down Lists](#form-lists)
- [Buttons](#form-buttons)
Almost every web application receives input through HTML forms. As you have probably already learned, Laravel is here to make your life easier. That's why generating forms using the **Form** class is a breeze.
> **Note:** All input data displayed in elements generated by the **Form** class is filtered through the HTML::entities method.
<a name="form-open"></a>
### Opening A Form
Opening a form is simple. Just call the **open** method on the Form class:
echo Form::open();
When called without any parameters, the open method will create a form that will POST to the current URL. However, you'll probably want to point your forms to other URLs too. No problem. Just mention the URL to the method. You can even specify the request method (GET, POST, PUT, or DELETE) in the second parameter to the method:
echo Form::open('user/profile', 'PUT');
Need to apply a class or other attribute to the form tag generated by the open method? Simply pass an array of attributes as a third parameter:
echo Form::open('user/profile', 'PUT', array('class' => 'awesome'));
> **Note:** The open method automatically prepares your form to receive UTF-8 input.
Need a form that can handle file uploads? Use the **open_for_files** method:
echo Form::open_for_files('user/profile');
<a name="form-csrf"></a>
### CSRF Protection
Laravel provides an easy method of protecting your application from [cross-site request forgeries](http://en.wikipedia.org/wiki/Cross-site_request_forgery). First, a random token is placed in your user's session. Don't sweat it, this is done automatically. Next, use the **token** method to generate a hidden form input field containing the random token on your form:
echo Form::token();
Now, simply [attach the built-in CSRF filter](/docs/start/routes#filters) to the route the form is posting to. If the token submitted by the form does not match the token in the user's session, the **application/views/error/500.php** view will be displayed.
Want to just get the CSRF token without generating a hidden input field? Use the **raw_token** method:
echo Form::raw_token();
> **Note:** Don't forget to [specify a session driver](/docs/session/config) before using these methods.
<a name="form-labels"></a>
### Labels
Need to generate a label for a form element? It's simple using the **label** method. Just pass the label name and display value to the method:
echo Form::label('email', 'E-Mail Address');
Of course, you may pass any attributes you wish in the third parameter to the method:
echo Form::label('email', 'E-Mail Address', array('class' => 'awesome'));
> **Note:** After creating a label, any form element you create with a name matching the label name will automatically receive an ID matching the label name as well.
<a name="form-text"></a>
### Text, Text Area, Password & Hidden Fields
Generating text boxes couldn't be easier. Just call the **text** method on the Form class and mention the name of the field:
echo Form::text('username');
Already have a value you want to put in the text box? Throw it in as a second parameter:
echo Form::text('email', 'example@gmail.com');
Again, any other attributes you wish to apply to the text box may be passed in an array as the third parameter:
echo Form::text('email', 'example@gmail.com', array('class' => 'awesome'));
> **Note:** The **password**, **hidden**, and **textarea** methods have the same signature as the text method. You just learned four methods for the price of one!
<a name="form-check"></a>
### Checkboxes & Radio Buttons
What website doesn't have a checkbox? Actually, this one doesn't! But, thankfully, generating them is simple using the **checkbox** method on the Form class. Just give the checkbox a name and a value:
echo Form::checkbox('remember', 'yes');
Of course, the example above will generate the following HTML:
<input type="checkbox" name="remember" value="yes">
Need to generate a "checked" checkbox? No problem. Simply pass **true** as the third parameter to the method:
echo Form::checkbox('remember', 'yes', true);
As always, you may specify any extra attributes that should be applied to the checkbox. Pass them as the fourth parameter to the method:
echo Form::checkbox('remember', 'yes', true, array('class' => 'awesome'));
> **Note:** The **radio** method has the same signature as the checkbox method. Two for one!
<a name="form-lists"></a>
### Drop-Down Lists
Generating drop-down lists can be a headache. Thankfully, Laravel makes it refreshingly simple using the **select** method on the Form class. All you need to do is give your list a name and an array of options:
echo Form::select('size', array('L' => 'Large', 'S' => 'Small'));
If you wish to set the selected item, just pass the value as the third parameter to the method:
echo Form::select('size', array('L' => 'Large', 'S' => 'Small'), 'S');
You may specify any other attributes that should be applied to the list in the fourth parameter to the method:
echo Form::select('size', array('L' => 'Large', 'S' => 'Small'), 'S', array('class' => 'awesome'));
<a name="form-buttons"></a>
### Buttons
Creating a submit button is a cinch. Use the **submit** method on the Form class:
echo Form::submit('Click Me!');
Again, any other attributes that should be applied to the button may be passed to the method:
echo Form::submit('Click Me!', array('class' => 'awesome'));
> **Note:** Need to create a button element? Try the **button** method. It has the same signature as submit.

View File

@@ -0,0 +1,124 @@
## Routes
- [Defining Routes](/docs/start/routes#define)
- [Wildcard URI Segments](/docs/start/routes#segments)
- [Named Routes](/docs/start/routes#named)
- [Route Filters](/docs/start/routes#filters)
- [Organizing Routes](/docs/start/routes#organize)
Unlike other PHP frameworks, Laravel places routes and their corresponding functions in one file: **application/routes.php**. This file contains the "definition", or public API, of your application. To add functionality to your application, you add to the array located in this file. It's a breeze.
<a name="define"></a>
## Defining Routes
All you need to do is tell Laravel the request methods and URIs it should respond to. You define the behavior of the route using an anonymous method:
'GET /home' => function()
{
// Handles GET requests to http://example.com/index.php/home
},
You can easily define a route to handle requests to more than one URI. Just use commas:
'POST /, POST /home' => function()
{
// Handles POST requests to http://example.com and http://example.com/home
}
> **Note:** The routes.php file replaces the "controllers" found in most frameworks. Have a fat model and keep this file light and clean. Thank us later.
<a name="segments"></a>
## Wildcard URI Segments
Laravel makes matching wildcard URI segments a breeze using the **(:num)** and **(:any)** place-holders. Check out these routes:
'PUT /user/(:num)' => function($id) {}
'DELETE /user/(:any)' => function($username) {}
Laravel will automatically pass the value of the wildcard segment into your route function.
> **Note:** The **(:any)** place-holder matches letters, number, dashes, and underscores.
Want to make an URI segment optional? No problem. Just put a **?** in the place-holder:
'GET /download/(:any?)' => function($branch = 'master') {}
If you need more power and precision (or just want to be extra nerdy), you can even use regular expressions:
'GET /product/([0-9]+)' => function($id) {}
<a name="named"></a>
## Named Routes
Once you start using named routes, you won't be able to live without them. They are that great. Here's how to do it:
'GET /user/login' => array('name' => 'login', 'do' => function() {})
Notice the route now has an array value with two keys: **name** and **do**. As you learned while studying filters, the **do** value is the method that will be executed by the route. As you have probably guessed, the **name** value is the name of the route.
Now that you have named the route, you can [generate URLs](/docs/start/views#urls) and [perform redirects](/docs/start/views#redirect) using the route name instead of the route URI. This means that you can change the route URI as much as you want and the links to that route on your views will always be correct. It's beautiful, isn't it?
<a name="filters"></a>
## Route Filters
Filters are methods that run before and after a request to your application. "Before" filters can even halt the request cycle by returning a response, providing an amazingly simple way to implement common tasks like redirecting a user to a login view. Let's dig in.
All filters are defined in the **application/filters.php** file. Intuitive, right? If you open the file, you will see that four filters have already been defined for you: **before**, **after**, **auth**, and **csrf**. The **before** and **after** filters are the two "global" filters. They are always executed on every request, regardless of the request method or URI.
All other filters must be attached to individual routes. Don't worry, you'll learn how to do this soon. The built-in **auth** and **csrf** filters handle two scenarios that are common to almost every web application: redirecting users to a login page and protecting against cross-site request forgeries.
### Defining Filters
To define your own filter, simply add it to the array in the **application/filters.php** file:
'my_filter' => function()
{
return 'Filtered!';
}
### Attaching Filters To Routes
Alright, ready to attach the filter to a route? Do it like this:
'GET /user' => array('before' => 'my_filter', 'do' => function()
{
//
})
Notice the route now has an array value with two keys: **before** and **do**. The **do** value is the method that will be executed by the route, while the **before** value contains the names of any filters that should be run before the method is executed.
Why stop with one filter? You can define multiple filters for a single route by separating the filter names with commas:
'POST /user' => array('before' => 'auth, csrf', 'do' => function() {})
Remember, if a "before" filter returns a value, that value will be considered the output of the request. For example, the built-in **auth** filter checks if the user has logged in to your application. If they haven't, a [Redirect](/docs/start/views#redirect) to the login page is sent to the browser. Isn't the simplicity refreshing?
Of course, adding filters to run after the request is just as easy:
'my_filter' => function($response) {}
'GET /user' => array('after' => 'my_filter', 'do' => function() {})
> **Note:** "After" filters receive the response returned by the route function that handled the request.
<a name="organize"></a>
## Organizing Routes
So, you're building the next monolithic web application and your **application/routes.php** file is getting a little cramped? Don't worry, we have you covered.
Here's what to do. First, create an **application/routes** directory. Great! You're almost there. Now, just add route files to **application/routes** corresponding to the base URIs of your application. So, a **photo.php** file within **application/routes** would handle all requests to URIs beginning with **/photo**. Similarly, a **user.php** file handles all requests to URIs beginning with **/user**. For example, check out this **user.php** file:
<?php
return array(
'GET /user/profile/(:num)' => function($id)
{
return View::make('user/profile');
}
);
The **application/routes.php** file will continue to be loaded on every request, so any "catch-all" routes can still be placed in that file. The **application/routes.php** file should also still contain the route for the root of your application.

View File

@@ -0,0 +1,368 @@
## Validation
- [The Basics](#basics)
- [Validation Rules](#rules)
- [Retrieving Error Messages](#errors)
- [Specifying Custom Error Messages](#messages)
- [Creating Custom Validation Rules](#custom)
<a name="basics"></a>
### The Basics
Almost every interactive web application needs to validate data. For instance, a registration form probably requires the password to be confirmed. Maybe the e-mail address must be unique. Validating data can be a cumbersome process. Thankfully, it isn't in Laravel. The **Validator** class provides as awesome array of validation helpers to make validating your data a breeze.
To get started, let's imagine we have the following array:
$array = array('name' => 'Taylor', 'email' => 'example@gmail.com');
Next, we're ready to define [validation rules](#rules) for our array:
$rules = array(
'name' => array('required', 'max:50'),
'email' => array('required', 'email', 'unique:users'),
);
If you don't like using arrays, you may also delimit rules using a pipe character:
$rules = array(
'name' => 'required|max:50',
'email' => 'required|email|unique:users',
);
Great! Now we're ready to make a **Validator** instance and validate our array:
$validator = Validator::make($array, $rules);
if ( ! $validator->valid())
{
return $validator->errors;
}
Via the **errors** property, you can access a simple error collector class that makes working with your error messages a breeze. Of course, default error messages have been setup for all validation rules. The default messages live in the **application/lang/en/validation.php** file.
Now you are familiar with the basic usage of the Validator class. You're ready to dig in and learn about the rules you can use to validate your data!
<a name="rules"></a>
### Validation Rules
- [Required](#rule-required)
- [Alpha, Alpha Numeric, & Alpha Dash](#rule-alphas)
- [Size](#rule-size)
- [Numericality](#rule-numeric)
- [Inclusion & Exclusion](#rule-inclusion)
- [Confirmation](#rule-confirmed)
- [Acceptance](#rule-accepted)
- [Uniqueness](#rule-unique)
- [E-Mail Addresses](#rule-email)
- [URLs](#rule-urls)
- [Uploads](#rule-uploads)
<a name="rule-required"></a>
#### Required
The **required** rule validates that an attribute is present in the array and is not an empty string:
$rules = array(
'name' => 'required',
);
<a name="rule-alphas"></a>
#### Alpha, Alpha Numeric, & Alpha Dash
The **alpha** rule validates that an attribute consists solely of letters:
$rules = array(
'name' => 'alpha',
);
The **alpha_num** rule validates that an attribute consists solely of letters and numbers:
$rules = array(
'username' => 'alpha_num',
);
The **alpha_dash** rule validates that an attribute consists solely of letters, numbers, dashes, and underscores:
$rules = array(
'username' => 'alpha_dash',
);
<a name="rule-size"></a>
#### Size
The **size** rule validates that an attribute is of a given length, or, if the attribute is numeric, is a given value:
$rules = array(
'name' => 'size:10',
);
The **between** rule validates that an attribute is between a given minimum and maximum:
$rules = array(
'payment' => 'between:10,50',
);
> **Note:** All minimum and maximum checks are inclusive.
The **min** rule validates that an attribute is greater than or equal to a given value:
$rules = array(
'payment' => 'min:10',
);
The **max** rule validates that an attribute is less than or equal to a given value:
$rules = array(
'payment' => 'max:50',
);
<a name="rule-numeric"></a>
#### Numericality
The **numeric** rule validates that an attribute is (surprise!) numeric:
$rules = array(
'payment' => 'numeric',
);
The **integer** rule validates that an attribute is an integer:
$rules = array(
'payment' => 'integer',
);
<a name="rule-inclusion"></a>
#### Inclusion & Exclusion
The **in** rule validates that an attribute is contained in a list of values:
$rules = array(
'size' => 'in:small,medium,large',
);
The **not_in** rule validates that an attribute is not contained in a list of values:
$rules = array(
'language' => 'not_in:cobol,assembler',
);
<a name="rule-confirmed"></a>
#### Confirmation
The **confirmed** rule validates that, for a given attribute, a matching **attribute_confirmation** attribute exists. For example, given the following rule:
$rules = array(
'password' => 'confirmed',
);
The Validator will make sure that the **password** attribute matches the **password_confirmation** attribute in the array being validated.
<a name="rule-accepted"></a>
#### Acceptance
The **accepted** rule validates that an attribute is equal to **yes** or **1**. This rule is helpful for validating checkbox form fields such as "terms of service".
$rules = array(
'terms' => 'accepted',
);
<a name="rule-unique"></a>
#### Uniqueness
The **unique** rule validates the uniqueness of an attribute on a given database table:
$rules = array(
'email' => 'unique:users',
);
In the example above, the **email** attribute will be checked for uniqueness on the **users** table. Need to verify uniqueness on a column name other than the attribute name? No problem:
$rules = array(
'email' => 'unique:users,email_address',
);
<a name="rule-email"></a>
#### E-Mail Addresses
The **email** rule validates that an attribute contains a correctly formatted e-mail address:
$rules = array(
'email' => 'email',
);
<a name="rule-urls"></a>
#### URLs
The **url** rule validates that an attribute contains a correctly formatted URL:
$rules = array(
'link' => 'url',
);
The **active_url** rule uses the PHP **checkdnsrr** function to verify that a URL is active:
$rules = array(
'link' => 'active_url',
);
<a name="rule-uploads"></a>
#### Uploads
The **mimes** rule validates that an uploaded file has a given MIME type. This rule uses the PHP Fileinfo extension to read the contents of the file and determine the actual MIME type. Any extension defined in the **application/config/mimes.php** file may be passed to this rule as a parameter:
$rules = array(
'picture' => 'mimes:jpg,gif',
);
$validator = Validator::make(Input::file(), $rules);
Need to validate form data and upload data at the same time? Use the **all** method on the **Input** class to get form and upload data in one array:
$validator = Validator::make(Input::all(), $rules);
The **image** rule validates that an uploaded file has a **jpg**, **gif**, **bmp**, or **png** MIME type:
$rules = array(
'picture' => 'image',
);
You may also validate the size of an upload using the **max** rule. Simply specify the maximum number of **kilobytes** the upload may be:
$rules = array(
'picture' => 'image|max:100',
);
<a name="errors"></a>
### Retrieving Error Messages
Laravel makes working with your error messages a cinch using a simple error collector class. After calling the **valid** or **invalid** method on a **Validator** instance, you may access the errors via the **errors** property:
if ( ! $validator->valid())
{
return $validator->errors;
}
The error collector has the following simple functions for retrieving your error messages: **has**, **first**, **get**, and **all**.
The **has** method will check if an error message exists for a given attribute:
if ($validator->errors->has('email'))
{
// The e-mail attribute has errors...
}
The **first** method will return the first error message for a given attribute:
echo $validator->errors->first('email');
Sometimes you may need to format the error message by wrapping it in HTML. No problem. Along with the **:message** place-holder, pass the format as the second parameter to the method:
echo $validator->errors->first('email', '<p>:message</p>');
The **get** method returns an array containing all of the error messages for a given attribute:
return $validator->errors->get('email');
return $validator->errors->get('email', '<p>:message</p>');
The **all** method returns an array containing all error messages for all attributes:
return $validator->errors->all();
return $validator->errors->all('<p>:message</p>');
<a name="messages"></a>
### Specifying Custom Error Messages
Want to use an error message other than the default? Maybe you even want to use a custom error message for a given attribute and rule. Either way, the **Validator** class makes it easy.
Simply create an array of custom messages to pass to the Validator instance:
$messages = array(
'required' => 'The :attribute field is required.',
);
$validator = Validator::make(Input::get(), $rules, $messages);
Great! Now our custom message will be used anytime a **required** validation check fails. But, what is this **:attribute** stuff in our message? To make your life easier, the Validator class will replace the **:attribute** place-holder with the actual name of the attribute! It will even remove underscores from the attribute name.
You may also use the **:size**, **:min**, **:max**, and **:values** place-holders when constructing your error messages:
$messages = array(
'size' => 'The :attribute must be exactly :size.',
'between' => 'The :attribute must be between :min - :max.',
'in' => 'The :attribute must be one of the following types: :values',
);
So, what if you need to specify a custom **required** message, but only for the **email** attribute? No problem. Just specify the message using an **attribute_rule** naming convention:
$messages = array(
'email_required' => 'We need to know your e-mail address!',
);
In the example above, the custom required message will be used for the **email** attribute, while the default message will be used for all other attributes.
<a name="custom"></a>
### Creating Custom Validation Rules
Need to create your own validation rules? You will love how easy it is! First, create a class that extends **System\Validator** and place it in your **application/libraries** directory:
<?php
class Validator extends System\Validator {}
Next, remove the **Validator** alias from **application/config/aliases.php**.
Alright! You're ready to define your own validation rule. Create a function on your new validator using a **validate_rule** naming convention:
<?php
class Validator extends System\Validator {
public function validate_awesome($attribute, $parameters)
{
return $attribute == 'awesome';
}
}
Let's dig into this example. The **validate_awesome** function receives two arguments. The first is the value of the attribute being validated, the second is an array of parameters that were specified for the rule, such as a size or list of accepted values (more on that in a second). Validator methods simply return **true** or **false**. It couldn't be any easier, right?
Now, how do you use your new validator? It's refreshingly simple:
$rules = array(
'username' => 'required|awesome',
);
Of course, you will need to define an error message for your new rule. You can do this either in an ad-hoc messages array:
$messages = array(
'awesome' => 'The attribute value must be awesome!',
);
$validator = Validator::make(Input::get(), $rules, $messages);
Or by adding an entry for your rule in the **application/lang/en/validation.php** file:
'awesome' => 'The attribute value must be awesome!',
As mentioned above, you may even specify and receive a list of parameters in your custom validator:
// When building your rules array...
$rules = array(
'username' => 'required|awesome:yes',
);
// In your custom validator...
class Validator extends System\Validator {
public function validate_awesome($attribute, $parameters)
{
return $attribute = $parameters[0];
}
}
In this case, the **parameters** argument of your validation rule would receive an array containing one element: "yes".

View File

@@ -0,0 +1,379 @@
## Views & Responses
- [Creating Views](/docs/start/views#create)
- [Binding Data To Views](/docs/start/views#bind)
- [Nesting Views Within Views](/docs/start/views#nest)
- [Redirects](/docs/start/views#redirect)
- [Downloads](/docs/start/views#downloads)
- [Building URLs](/docs/start/views#urls)
- [Building HTML](/docs/start/views#html)
<a name="create"></a>
## Creating Views
Typically, a route function returns a **View**. Views consist of plain ole' HTML and are stored in your **application/views** directory.
A very simple view file could look like this:
<html>
Welcome to my website!
</html>
Assuming this view lives in **application/views/simple.php**, we could return it from a route like so:
'GET /home' => function()
{
return View::make('simple');
}
When building a large application, you may want to organize your views into sub-directories. That's a great idea! Assuming a view lives in **application/views/user/login.php**, we could return it like so:
'GET /home' => function()
{
return View::make('user/login');
}
It's that simple. Of course, you are not required to return a View. Strings are also welcome:
'GET /home' => function()
{
return json_encode('This is my response!');
}
<a name="bind"></a>
## Binding Data To Views
You can pass data to a view by "binding" the data to a variable. This is done using the **bind** method on the View:
'GET /home' => function()
{
return View::make('simple')->bind('email', 'example@gmail.com');
}
In the example above, the first parameter is the **name** of the view variable. The second parameter is the **value** that will be assigned to the variable.
Now, in our view, we can access the e-mail address like so:
<html>
<?php echo $email; ?>
</html>
Of course, we can bind as many variables as we wish:
'GET /home' => function()
{
return View::make('simple')
->bind('name', 'Taylor')
->bind('email', 'example@gmail.com');
}
You may also bind view data by simply setting properties on a view instance:
'GET /home' => function()
{
$view = View::make('user/login');
$view->name = 'Taylor';
$view->email = 'example@gmail.com';
return $view;
}
<a name="nest"></a>
## Nesting Views Within Views
Want to nest views inside of views? There are two ways to do it, and they are both easy. First, you can bind the view to a variable:
'GET /home' => function()
{
$view = View::make('user/login');
$view->content = View::make('partials/content');
$view->footer = View::make('partials/footer');
return $view;
}
Or, you can get the string content of a view using the **get** method:
<html>
<?php echo View::make('content')->get(); ?>
<?php echo View::make('footer')->get(); ?>
</html>
<a name="redirect"></a>
## Redirects
### Redirect Using URIs
You will often need to redirect the browser to another location within your application. The **Redirect** class makes this a piece of cake. Here's how to do it:
'GET /redirect' => function()
{
return Redirect::to('user/profile');
}
Of course, you can also redirect to the root of your application:
return Redirect::to('/');
Need to redirect to a URI that should be accessed over HTTPS? Check out the **to_secure** method:
return Redirect::to_secure('user/profile');
You can even redirect the browser to a location outside of your application:
return Redirect::to('http://www.google.com/');
<a name="named"></a>
### Redirect Using Named Routes
So far we've created redirects by specifying a URI to redirect to. But, what if the URI to the user's profile changes? It would be better to create a redirect based on the [route name](/docs/start/routes#named). Let's learn how to do it. Assuming the user profile route is named **profile**, you can redirect to the route using a dynamic, static method call like this:
return Redirect::to_profile();
Need to redirect to a route that should be accessed over HTTPS? No problem:
return Redirect::to_secure_profile();
That's great! But, what if the route URI looks like this:
'GET /user/profile/(:any)/(:any)' => array('name' => 'profile', 'do' => function()
{
//
})
You need to redirect to the named route, but you also need to replace the **(:any)** place-holders in the URI with actual values. It sounds complicated, but Laravel makes it a breeze. Just pass the parameters to the method in an array:
return Redirect::to_profile(array('taylor', 'otwell'));
The statement above will redirect the user to the following URL:
http://example.com/index.php/user/profile/taylor/otwell
<a name="with"></a>
### Redirect With Flash Data
After a user creates an account or signs into your application, it is common to display a welcome or status message. But, how can you set the status message so it is available for the next request? The **Response** and **Redirect** classes make it simple using the **with** method. This method will add a value to the Session flash data, which will be available for the next request:
return Redirect::to('user/profile')->with('status', 'Welcome Back!');
> **Note:** For more information regarding Sessions and flash data, check out the [Session documentation](/docs/session/config).
<a name="downloads"></a>
## Downloads
Perhaps you just want to force the web browser to download a file? Check out the **download** method on the **File** class:
'GET /file' => function()
{
return File::download('path/to/your/file.jpg');
}
In the example above, the image will be downloaded as "file.jpg", however, you can easily specify a different filename for the download in the second parameter to the method:
'GET /file' => function()
{
return File::download('path/to/your/file.jpg', 'photo.jpg');
}
<a name="urls"></a>
## Building URLs
- [Generating URLs Using URIs](#uri-urls)
- [Generating URLs Using Named Routes](#named-urls)
- [URL Slugs](#url-slugs)
While developing your application, you will probably need to generate a large number of URLs. Hard-coding your URLs can cause headaches if you switch domains or application locations. Nobody wants to dig through every view in their application to change URLs. Thankfully, the **URL** class provides some simple methods that allow you to easily generate URLs for your application.
<a name="uri-urls"></a>
### Generating URLs Using URIs
To generate a URL for your application, use the **to** method on the URL class:
echo URL::to();
The statement above will simply return the URL specified in your **application/config/application.php** file.
However, this method can also append a specified string to the end of your application URL:
echo URL::to('user/profile');
Now the statement will generate a URL something like this:
http://example.com/index.php/user/login
Need to generate a HTTPS URL? No problem. Check out the **to\_secure** method:
echo URL::to_secure('user/profile');
Often, you will need to generate URLs to assets such as images, scripts, or styles. You don't want "index.php" inserted into these URLs. So, use the **to_asset** method:
echo URL::to_asset('img/picture.jpg');
<a name="named-urls"></a>
### Generating URLs To Named Routes
Alright, you have learned how to generate URLs from URIs, but what about from named routes? You can do it by making a dynamic, static method call to the URL class. The syntax is beautiful:
echo URL::to_profile();
Have a route that needs to be accessed over HTTPS? No problem:
echo URL::to_secure_profile();
Could it get any easier? Now, imagine a route that is defined like this:
'GET /user/profile/(:any)/(:any)' => array('name' => 'profile', 'do' => function()
{
//
})
To generate a URL for the route, you need to replace the **(:any)** place-holders with actual values. It's easy. Just pass the parameters to the method in an array:
echo URL::to_profile(array('taylor', 'otwell'));
The method above will generate the following URL:
http://example.com/index.php/user/profile/taylor/otwell
If you don't want to use dynamic methods, you can simply call the **to_route** method:
echo URL::to_route('profile', array('taylor', 'otwell'));
<a name="url-slugs"></a>
### URL Slugs
When writing an application like a blog, it is often necessary to generate URL "slugs". Slugs are URL friendly strings of text that represent something like a blog post title. Generating slugs is a piece of cake using the **slug** method:
echo URL::slug('My blog post title!');
The statement above will return the following string:
my-blog-post-title
Want to use a different separator character? Just mention it to the method:
echo URL::slug('My blog post title!', '_');
<a name="html"></a>
## Building HTML
- [Entities](#html-entities)
- [JavaScript & Style Sheets](#html-styles)
- [Links](#html-links)
- [Links To Named Routes](#html-route-links)
- [Mail-To Links](#html-mailto)
- [Images](#html-images)
- [Lists](#html-lists)
Need some convenient methods that make writing HTML a little less painful? Introducing the **HTML** class. Enjoy.
<a name="html-entities"></a>
### Entities
When displaying user input in your Views, it is important to convert all characters which have signifance in HTML to their "entity" representation.
For example, the < symbol should be converted to its entity representation. Converting HTML characters to their entity representation helps protect your application from cross-site scripting. Thankfully, using the **entities** method on the HTML class, it's easy to add this layer of protection to your Views:
echo HTML::entities('<script>alert('hi');</script>');
<a name="html-styles"></a>
### JavaScript & Style Sheets
What trendy web application doesn't use JavaScript? Generating a reference to a JavaScript file is as simple using the **script** method.
echo HTML::script('js/scrollTo.js');
Referencing cascading style sheets is just as simple. Check out the **style method**:
echo HTML::style('css/common.css');
Need to specify a media type on your style sheet? No problem. Just pass it in the second parameter to the method:
echo HTML::style('css/common.css', 'print');
> **Note:** All scripts and stylesheets should live in the **public** directory of your application.
<a name="html-links"></a>
### Links
Generating links couldn't be easier. Just mention the URL and title to the **link** method:
echo HTML::link('user/profile', 'User Profile');
Need to generate a link to a URL that should be accessed over HTTPS? Use the **secure_link** method:
echo HTML::secure_link('user/profile', 'User Profile');
Of course, you may generate links to locations outside of your application:
echo HTML::link('http://www.google.com', 'Search the Intrawebs!');
Any other attributes that should be applied to the link may be passed in the third parameter to the method:
echo HTML::link('http://www.google.com', 'Search the Intrawebs!', array('id' => 'google'));
<a name="html-route-links"></a>
### Links To Named Routes
If you are using [named routes](#routes-named), you use intuitive, expressive syntax to create links to those routes via dynamic methods:
echo HTML::link_to_login('Login');
Or, if you need an HTTPS link:
echo HTML::link_to_secure_login('Login');
Now let's assume the **login** route is defined like this:
'GET /login/(:any)' => array('name' => 'login', 'do' => function() {})
To generate a link to the route, you need to replace the **(:any)** place-holder with an actual value. It's easy. Just pass the parameters to the method in an array:
echo HTML::link_to_login(array('user'));
This statement will generate a link to the following URL:
http://example.com/login/user
<a name="html-mailto"></a>
### Mail-To Links
It's great to allow your users to get in touch with you, but you don't want to be bombarded by spam. Laravel doesn't want you to be either. The **mailto** method allows you to create a safe mail-to link that obfuscates your e-mail address:
echo HTML::mailto('example@gmail.com');
Want the link text to be something besides your e-mail address? No problem. Just mention it to the method:
echo HTML::mailto('example@gmail.com', 'E-Mail Me!');
Need to obfuscate an e-mail address but don't want to generate an entire mail-to link? Simply pass the e-mail address to the **email** method:
echo HTML::email('example@gmail.com');
<a name="html-images"></a>
### Images
Since you're building a creative application, you will need to include some images. The **image** method makes simple. Just pass the URL and Alt text to the method:
echo HTML::image('img/smile.jpg', 'A Smiling Face');
Like the link method, any other attributes that should be applied to the image may be passed in the third parameter to the method:
echo HTML::image('img/smile.jpg', 'A Smiling Face', array('id' => 'smile'));
<a name="html-lists"></a>
### Lists
Generating HTML lists doesn't have to be a headache. Check out the **ol** method. All it needs is an array of items:
echo HTML::ol(array('Get Peanut Butter', 'Get Chocolate', 'Feast'));
As usual, you may specify any other attributes that should be applied to the list:
echo HTML::ol(array('Get Peanut Butter', 'Get Chocolate', 'Feast'), array('class' => 'awesome'));
Need an un-ordered list? No problem. Just use the **ul** method:
echo HTML::ul(array('Ubuntu', 'Snow Leopard', 'Windows'));