move documentation into bundle.

This commit is contained in:
Taylor Otwell
2012-04-03 09:51:56 -05:00
parent fdb7b3a7f3
commit e66d8943d1
44 changed files with 2 additions and 2 deletions

View File

@@ -0,0 +1,46 @@
# 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.

View File

@@ -0,0 +1,487 @@
# Eloquent ORM
## Contents
- [The Basics](#the-basics)
- [Conventions](#conventions)
- [Retrieving Models](#get)
- [Aggregates](#aggregates)
- [Inserting & Updating Models](#save)
- [Relationships](#relationships)
- [Inserting Related Models](#inserting-related-models)
- [Working With Intermediate Tables](#intermediate-tables)
- [Eager Loading](#eager)
- [Constraining Eager Loads](#constraining-eager-loads)
- [Setter & Getter Methods](#getter-and-setter-methods)
- [Mass-Assignment](#mass-assignment)
- [Converting Models To Arrays](#to-array)
<a name="the-basics"></a>
## The Basics
An ORM is an [object-relational mapper](http://en.wikipedia.org/wiki/Object-relational_mapping), and Laravel has one that you will absolutely love to use. It is named "Eloquent" because it allows you to work with your database objects and relationships using an eloquent and expressive syntax. In general, you will define one Eloquent model for each table in your database. To get started, let's define a simple model:
class User extends Eloquent {}
Nice! Notice that our model extends the **Eloquent** class. This class will provide all of the functionality you need to start working eloquently with your database.
> **Note:** Typically, Eloquent models live in the **application/models** directory.
<a name="conventions"></a>
## Conventions
Eloquent makes a few basic assumptions about your database structure:
- Each table should have a primary key named **id**.
- Each table name should be the plural form of its corresponding model name.
Sometimes you may wish to use a table name other than the plural form of your model. No problem. Just add a static **table** property your model:
class User extends Eloquent {
public static $table = 'my_users';
}
<a name="get"></a>
## Retrieving Models
Retrieving models using Eloquent is refreshingly simple. The most basic way to retrieve an Eloquent model is the static **find** method. This method will return a single model by primary key with properties corresponding to each column on the table:
$user = User::find(1);
echo $user->email;
The find method will execute a query that looks something like this:
SELECT * FROM "users" WHERE "id" = 1
Need to retrieve an entire table? Just use the static **all** method:
$users = User::all();
foreach ($users as $user)
{
echo $user->email;
}
Of course, retrieving an entire table isn't very helpful. Thankfully, **every method that is available through the fluent query builder is available in Eloquent**. Just begin querying your model with a static call to one of the [query builder](/docs/database/query) methods, and execute the query using the **get** or **first** method. The get method will return an array of models, while the first method will return a single model:
$user = User::where('email', '=', $email)->first();
$user = User::where_email($email)->first();
$users = User::where_in('id', array(1, 2, 3))->or_where('email', '=', $email)->get();
$users = User::order_by('votes', 'desc')->take(10)->get();
> **Note:** If no results are found, the **first** method will return NULL. The **all** and **get** methods return an empty array.
<a name="aggregates"></a>
## Aggregates
Need to get a **MIN**, **MAX**, **AVG**, **SUM**, or **COUNT** value? Just pass the column to the appropriate method:
$min = User::min('id');
$max = User::max('id');
$avg = User::avg('id');
$sum = User::sum('id');
$count = User::count();
Of course, you may wish to limit the query using a WHERE clause first:
$count = User::where('id', '>', 10)->count();
<a name="save"></a>
## Inserting & Updating Models
Inserting Eloquent models into your tables couldn't be easier. First, instantiate a new model. Second, set its properties. Third, call the **save** method:
$user = new User;
$user->email = 'example@gmail.com';
$user->password = 'secret';
$user->save();
Alternatively, you may use the **create** method, which will insert a new record into the database and return the model instance for the newly inserted record, or **false** if the insert failed.
$user = User::create(array('email' => 'example@gmail.com'));
Updating models is just as simple. Instead of instantiating a new model, retrieve one from your database. Then, set its properties and save:
$user = User::find(1);
$user->email = 'new_email@gmail.com';
$user->password = 'new_secret';
$user->save();
Need to maintain creation and update timestamps on your database records? With Eloquent, you don't have to worry about it. Just add a static **timestamps** property to your model:
class User extends Eloquent {
public static $timestamps = true;
}
Next, add **created_at** and **updated_at** date columns to your table. Now, whenever you save the model, the creation and update timestamps will be set automatically. You're welcome.
> **Note:** You can change the default timezone of your application in the **application/config/application.php** file.
<a name="relationships"></a>
## Relationships
Unless you're doing it wrong, your database tables are probably related to one another. For instance, an order may belong to a user. Or, a post may have many comments. Eloquent makes defining relationships and retrieving related models simple and intuitive. Laravel supports three types of relationships:
- [One-To-One](#one-to-one)
- [One-To-Many](#one-to-many)
- [Many-To-Many](#many-to-many)
To define a relationship on an Eloquent model, you simply create a method that returns the result of either the **has\_one**, **has\_many**, **belongs\_to**, or **has\_many\_and\_belongs\_to** method. Let's examine each one in detail.
<a name="one-to-one"></a>
### One-To-One
A one-to-one relationship is the most basic form of relationship. For example, let's pretend a user has one phone. Simply describe this relationship to Eloquent:
class User extends Eloquent {
public function phone()
{
return $this->has_one('Phone');
}
}
Notice that the name of the related model is passed to the **has_one** method. You can now retrieve the phone of a user through the **phone** method:
$phone = User::find(1)->phone()->first();
Let's examine the SQL performed by this statement. Two queries will be performed: one to retrieve the user and one to retrieve the user's phone:
SELECT * FROM "users" WHERE "id" = 1
SELECT * FROM "phones" WHERE "user_id" = 1
Note that Eloquent assumes the foreign key of the relationship will be **user\_id**. Most foreign keys will follow this **model\_id** convention; however, if you want to use a different column name as the foreign key, just pass it in the second parameter to the method:
return $this->has_one('Phone', 'my_foreign_key');
Want to just retrieve the user's phone without calling the first method? No problem. Just use the **dynamic phone property**. Eloquent will automatically load the relationship for you, and is even smart enough to know whether to call the get (for one-to-many relationships) or first (for one-to-one relationships) method:
$phone = User::find(1)->phone;
What if you need to retrieve a phone's user? Since the foreign key (**user\_id**) is on the phones table, we should describe this relationship using the **belongs\_to** method. It makes sense, right? Phones belong to users. When using the **belongs\_to** method, the name of the relationship method should correspond to the foreign key (sans the **\_id**). Since the foreign key is **user\_id**, your relationship method should be named **user**:
class Phone extends Eloquent {
public function user()
{
return $this->belongs_to('User');
}
}
Great! You can now access a User model through a Phone model using either your relationship method or dynamic property:
echo Phone::find(1)->user()->first()->email;
echo Phone::find(1)->user->email;
<a name="one-to-many"></a>
### One-To-Many
Assume a blog post has many comments. It's easy to define this relationship using the **has_many** method:
class Post extends Eloquent {
public function comments()
{
return $this->has_many('Comment');
}
}
Now, simply access the post comments through the relationship method or dynamic property:
$comments = Post::find(1)->comments()->get();
$comments = Post::find(1)->comments;
Both of these statements will execute the following SQL:
SELECT * FROM "posts" WHERE "id" = 1
SELECT * FROM "comments" WHERE "post_id" = 1
Want to join on a different foreign key? No problem. Just pass it in the second parameter to the method:
return $this->has_many('Comment', 'my_foreign_key');
You may be wondering: _If the dynamic properties return the relationship and require less keystokes, why would I ever use the relationship methods?_ Actually, relationship methods are very powerful. They allow you to continue to chain query methods before retrieving the relationship. Check this out:
echo Post::find(1)->comments()->order_by('votes', 'desc')->take(10)->get();
<a name="many-to-many"></a>
### Many-To-Many
Many-to-many relationships are the most complicated of the three relationships. But don't worry, you can do this. For example, assume a User has many Roles, but a Role can also belong to many Users. Three database tables must be created to accomplish this relationship: a **users** table, a **roles** table, and a **role_user** table. The structure for each table looks like this:
**Users:**
id - INTEGER
email - VARCHAR
**Roles:**
id - INTEGER
name - VARCHAR
**Roles_Users:**
user_id - INTEGER
role_id - INTEGER
Now you're ready to define the relationship on your models using the **has\_many\_and\_belongs\_to** method:
class User extends Eloquent {
public function roles()
{
return $this->has_many_and_belongs_to('Role');
}
}
Great! Now it's time to retrieve a user's roles:
$roles = User::find(1)->roles()->get();
Or, as usual, you may retrieve the relationship through the dynamic roles property:
$roles = User::find(1)->roles;
As you may have noticed, the default name of the intermediate table is the singular names of the two related models arranged alphabetically and concatenated by an underscore. However, you are free to specify your own table name. Simply pass the table name in the second parameter to the **has\_and\_belongs\_to\_many** method:
class User extends Eloquent {
public function roles()
{
return $this->has_many_and_belongs_to('Role', 'user_roles');
}
}
<a name="inserting-related-models"></a>
## Inserting Related Models
Let's assume you have a **Post** model that has many comments. Often you may want to insert a new comment for a given post. Instead of manually setting the **post_id** foreign key on your model, you may insert the new comment from it's owning Post model. Here's what it looks like:
$comment = new Comment(array('message' => 'A new comment.'));
$post = Post::find(1);
$post->comments()->insert($comment);
When inserting related models through their parent model, the foreign key will automatically be set. So, in this case, the "post_id" was automatically set to "1" on the newly inserted comment.
This is even more helpful when working with many-to-many relationships. For example, consider a **User** model that has many roles. Likewise, the **Role** model may have many users. So, the intermediate table for this relationship has "user_id" and "role_id" columns. Now, let's insert a new Role for a User:
$role = new Role(array('title' => 'Admin'));
$user = User::find(1);
$user->roles()->insert($role);
Now, when the Role is inserted, not only is the Role inserted into the "roles" table, but a record in the intermediate table is also inserted for you. It couldn't be easier!
However, you may often only want to insert a new record into the intermediate table. For example, perhaps the role you wish to attach to the user already exists. Just use the attach method:
$user->roles()->attach($role_id);
<a name="sync-method"></a>
Alternatively, you can use the `sync` method, which accepts an array of IDs to "sync" with the intermediate table. After this operation is complete, only the IDs in the array will be on the intermediate table.
$user->roles()->sync(array(1, 2, 3));
<a name="intermediate-tables"></a>
## Working With Intermediate Tables
As your probably know, many-to-many relationships require the presence of an intermediate table. Eloquent makes it a breeze to maintain this table. For example, let's assume we have a **User** model that has many roles. And, likewise, a **Role** model that has many users. So the intermediate table has "user_id" and "role_id" columns. We can access the pivot table for the relationship like so:
$user = User::find(1);
$pivot = $user->roles()->pivot();
Once we have an instance of the pivot table, we can use it just like any other Eloquent model:
foreach ($user->roles()->pivot()->get() as $row)
{
//
}
You may also access the specific intermediate table row associated with a given record. For example:
$user = User::find(1);
foreach ($user->roles as $role)
{
echo $role->pivot->created_at;
}
Notice that each related **Role** model we retrieved is automatically assigned a **pivot** attribute. This attribute contains a model representing the intermediate table record associated with that related model.
Sometimes you may wish to remove all of the record from the intermediate table for a given model relationship. For instance, perhaps you want to remove all of the assigned roles from a user. Here's how to do it:
$user = User::find(1);
$user->roles()->delete();
Note that this does not delete the roles from the "roles" table, but only removes the records from the intermediate table which associated the roles with the given user.
<a name="eager"></a>
## Eager Loading
Eager loading exists to alleviate the N + 1 query problem. Exactly what is this problem? Well, pretend each Book belongs to an Author. We would describe this relationship like so:
class Book extends Eloquent {
public function author()
{
return $this->belongs_to('Author');
}
}
Now, examine the following code:
foreach (Book::all() as $book)
{
echo $book->author->name;
}
How many queries will be executed? Well, one query will be executed to retrieve all of the books from the table. However, another query will be required for each book to retrieve the author. To display the author name for 25 books would require **26 queries**. See how the queries can add up fast?
Thankfully, you can eager load the author models using the **with** method. Simply mention the **function name** of the relationship you wish to eager load:
foreach (Book::with('author')->get() as $book)
{
echo $book->author->name;
}
In this example, **only two queries will be executed**!
SELECT * FROM "books"
SELECT * FROM "authors" WHERE "id" IN (1, 2, 3, 4, 5, ...)
Obviously, wise use of eager loading can dramatically increase the performance of your application. In the example above, eager loading cut the execution time in half.
Need to eager load more than one relationship? It's easy:
$books = Book::with(array('author', 'publisher'))->get();
> **Note:** When eager loading, the call to the static **with** method must always be at the beginning of the query.
You may even eager load nested relationships. For example, let's assume our **Author** model has a "contacts" relationship. We can eager load both of the relationships from our Book model like so:
$books = Book::with(array('author', 'author.contacts'))->get();
<a name="constraining-eager-loads"></a>
## Constraining Eager Loads
Sometimes you may wish to eager load a relationship, but also specify a condition for the eager load. It's simple. Here's what it looks like:
$users = User::with(array('posts' => function($query)
{
$query->where('title', 'like', '%first%');
}))->get();
In this example, we're eager loading the posts for the users, but only if the post's "title" column contains the word "first".
<a name="getter-and-setter-methods"></a>
## Getter & Setter Methods
Setters allow you to handle attribute assignment with custom methods. Define a setter by appending "set_" to the intended attribute's name.
public function set_password($password)
{
$this->set_attribute('hashed_password', Hash::make($password));
}
Call a setter method as a variable (without parenthesis) using the name of the method without the "set_" prefix.
$this->password = "my new password";
Getters are very similar. They can be used to modify attributes before they're returned. Define a getter by appending "get_" to the intended attribute's name.
public function get_published_date()
{
return date('M j, Y', $this->get_attribute('published_at'));
}
Call the getter method as a variable (without parenthesis) using the name of the method without the "get_" prefix.
echo $this->published_date;
<a name="mass-assignment"></a>
## Mass-Assignment
Mass-assignment is the practice of passing an associative array to a model method which then fills the model's attributes with the values from the array. Mass-assignment can be done by passing an array to the model's constructor:
$user = new User(array(
'username' => 'first last',
'password' => 'disgaea'
));
$user->save();
Or, mass-assignment may be accomplished using the **fill** method.
$user = new User;
$user->fill(array(
'username' => 'first last',
'password' => 'disgaea'
));
$user->save();
By default, all attribute key/value pairs will be store during mass-assignment. However, it is possible to create a white-list of attributes that will be set. If the accessible attribute white-list is set then no attributes other than those specified will be set during mass-assignment.
You can specify accessible attributes by assigning the **$accessible** static array. Each element contains the name of a white-listed attribute.
public static $accessible = array('email', 'password', 'name');
Alternatively, you may use the **accessible** method from your model:
User::accessible(array('email', 'password', 'name'));
> **Note:** Utmost caution should be taken when mass-assigning using user-input. Technical oversights could cause serious security vulnerabilities.
<a name="to-array"></a>
## Converting Models To Arrays
When building JSON APIs, you will often need to convert your models to array so they can be easily serialized. It's really simple.
#### Convert a model to an array:
return json_encode($user->to_array());
The `to_array` method will automatically grab all of the attributes on your model, as well as any loaded relationships.
Sometimes you may wish to limit the attributes that are included in your model's array, such as passwords. To do this, add a `hidden` attribute definition to your model:
#### Excluding attributes from the array:
class User extends Eloquent {
public static $hidden = array('password');
}

View File

@@ -0,0 +1,270 @@
# 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);

View File

@@ -0,0 +1,72 @@
# 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

View File

@@ -0,0 +1,56 @@
# 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.

View File

@@ -0,0 +1,58 @@
# 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.

View File

@@ -0,0 +1,141 @@
# 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');