Commit 9f803519 authored by Taylor Otwell's avatar Taylor Otwell

Merge branch 'develop' into feature/http-foundation

parents 4c2406db ff484b72
......@@ -33,4 +33,10 @@
|
*/
return array();
\ No newline at end of file
return array(
// route the official docs
'docs' => array(
'handles' => 'docs'
),
);
\ No newline at end of file
This diff is collapsed.
<?php
require_once __DIR__.'/libraries/markdown.php';
View::composer('docs::template', function($view)
{
Asset::add('stylesheet', 'laravel/css/style.css');
Asset::add('modernizr', 'laravel/js/modernizr-2.5.3.min.js');
Asset::container('footer')->add('prettify', 'laravel/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)
{
$root = path('storage').'documentation/';
$file = rtrim(implode('/', array($section, $page)), '/').'.md';
if (file_exists($path = $root.$file))
{
$content = Markdown(file_get_contents($path));
}
elseif (file_exists($path = $root.$section.'/home.md'))
{
$content = Markdown(file_get_contents($path));
}
else
{
return Response::error('404');
}
return View::make('docs::page')->with('content', $content);
});
\ No newline at end of file
@layout('docs::template')
@section('content')
<h1>Learn the terrain.</h1>
<p>
You've landed yourself on our default home page. The route that
is generating this page lives in the main routes file. You can
find it here:
</p>
<pre>APP_PATH/routes.php</pre>
<!--
<pre class="prettyprint lang-php linenums">
return array(
'welcome' => 'Welcome to our website!',
);
</pre>
-->
<p>And the view sitting before you can be found at:</p>
<pre>APP_PATH/views/home/index.php</pre>
<h1>Create something beautiful.</h1>
<p>
Now that you're up and running, it's time to start creating!
Here are some links to help you get started:
</p>
<ul>
<li><a href="http://laravel.com">Official Website</a></li>
<li><a href="http://forums.laravel.com">Laravel Forums</a></li>
<li><a href="http://github.com/laravel/laravel">GitHub Repository</a></li>
</ul>
@endsection
<h2>Documentation</h2>
<ul>
<li><a href="#">Menu Item</a></li>
<li><a href="#">Menu Item</a></li>
<li><a href="#">Menu Item</a>
<ul>
<li><a href="#">Sub Menu Item</a></li>
<li><a href="#">Sub Menu Item</a></li>
</ul>
</li>
<li><a href="#">Menu Item</a></li>
<li><a href="#">Menu Item</a></li>
<li><a href="#">Menu Item</a>
<ul>
<li><a href="#">Sub Menu Item</a></li>
<li><a href="#">Sub Menu Item</a></li>
<li><a href="#">Sub Menu Item</a></li>
</ul>
</li>
<li><a href="#">Menu Item</a></li>
<li><a href="#">Menu Item</a></li>
<li><a href="#">Menu Item</a></li>
<li><a href="#">Menu Item</a></li>
<li><a href="#">Menu Item</a></li>
<li><a href="#">Menu Item</a></li>
<li><a href="#">Menu Item</a></li>
</ul>
\ No newline at end of file
@layout('docs::template')
@section('content')
{{ $content }}
@endsection
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Laravel: A Framework For Web Artisans</title>
<meta name="viewport" content="width=device-width">
{{ Asset::styles(); }}
{{ Asset::scripts(); }}
</head>
<body onload="prettyPrint()">
<div class="wrapper">
<header>
<h1>Laravel</h1>
<h2>A Framework For Web Artisans</h2>
<p class="intro-text">
You have successfully installed the Laravel framework. Laravel is a simple framework
that helps web artisans create beautiful, creative applications using elegant, expressive
syntax. You'll love using it.
</p>
</header>
<div role="main" class="main">
<aside class="sidebar">
{{ $sidebar }}
</aside>
<div class="content">
@yield('content')
</div>
</div>
</div>
{{ Asset::container('footer')->scripts(); }}
</body>
</html>
......@@ -24,6 +24,7 @@
- Added "$hidden" static variable to the base Eloquent model.
- Added "sync" method to has_many_and_belongs_to Eloquent relationship.
- Improved View performance by only loading contents from file once.
- Fix handling of URLs beginning with has in URL::to.
<a name="upgrade-3.2"></a>
## Upgrading From 3.1
......
......@@ -95,7 +95,13 @@ class URL {
*/
public static function to($url = '', $https = false)
{
if (filter_var($url, FILTER_VALIDATE_URL) !== false) return $url;
// If the given URL is already valid or begins with a hash, we'll just return
// the URL unchanged since it is already well formed. Otherwise we will add
// the base URL of the application and return the full URL.
if (static::valid($url) or starts_with($url, '#'))
{
return $url;
}
$root = static::base().'/'.Config::get('application.index');
......@@ -288,4 +294,15 @@ class URL {
return trim($uri, '/');
}
/**
* Determine if the given URL is valid.
*
* @param string $url
* @return bool
*/
public static function valid($url)
{
return filter_var($url, FILTER_VALIDATE_URL) !== false;
}
}
\ No newline at end of file
......@@ -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);
}
}
......
@import url(http://fonts.googleapis.com/css?family=Droid+Sans);
article, aside, details, figcaption, figure, footer, header, hgroup, nav, section { display: block; }
audio, canvas, video { display: inline-block; *display: inline; *zoom: 1; }
audio:not([controls]) { display: none; }
[hidden] { display: none; }
html { font-size: 100%; -webkit-text-size-adjust: 100%; -ms-text-size-adjust: 100%; }
html, button, input, select, textarea { font-family: sans-serif; color: #222; }
body { margin: 0; font-size: 1em; line-height: 1.4; }
::-moz-selection { background: #E37B52; color: #fff; text-shadow: none; }
::selection { background: #E37B52; color: #fff; text-shadow: none; }
a { color: #00e; }
a:visited { color: #551a8b; }
a:hover { color: #06e; }
a:focus { outline: thin dotted; }
a:hover, a:active { outline: 0; }
abbr[title] { border-bottom: 1px dotted; }
b, strong { font-weight: bold; }
blockquote { margin: 1em 40px; }
dfn { font-style: italic; }
hr { display: block; height: 1px; border: 0; border-top: 1px solid #ccc; margin: 1em 0; padding: 0; }
ins { background: #ff9; color: #000; text-decoration: none; }
mark { background: #ff0; color: #000; font-style: italic; font-weight: bold; }
pre, code, kbd, samp { font-family: monospace, serif; _font-family: 'courier new', monospace; font-size: 1em; }
pre { white-space: pre; white-space: pre-wrap; word-wrap: break-word; }
q { quotes: none; }
q:before, q:after { content: ""; content: none; }
small { font-size: 85%; }
sub, sup { font-size: 75%; line-height: 0; position: relative; vertical-align: baseline; }
sup { top: -0.5em; }
sub { bottom: -0.25em; }
ul, ol { margin: 1em 0; padding: 0 0 0 40px; }
dd { margin: 0 0 0 40px; }
nav ul, nav ol { list-style: none; list-style-image: none; margin: 0; padding: 0; }
img { border: 0; -ms-interpolation-mode: bicubic; vertical-align: middle; }
svg:not(:root) { overflow: hidden; }
figure { margin: 0; }
form { margin: 0; }
fieldset { border: 0; margin: 0; padding: 0; }
label { cursor: pointer; }
legend { border: 0; *margin-left: -7px; padding: 0; white-space: normal; }
button, input, select, textarea { font-size: 100%; margin: 0; vertical-align: baseline; *vertical-align: middle; }
button, input { line-height: normal; }
button, input[type="button"], input[type="reset"], input[type="submit"] { cursor: pointer; -webkit-appearance: button; *overflow: visible; }
button[disabled], input[disabled] { cursor: default; }
input[type="checkbox"], input[type="radio"] { box-sizing: border-box; padding: 0; *width: 13px; *height: 13px; }
input[type="search"] { -webkit-appearance: textfield; -moz-box-sizing: content-box; -webkit-box-sizing: content-box; box-sizing: content-box; }
input[type="search"]::-webkit-search-decoration, input[type="search"]::-webkit-search-cancel-button { -webkit-appearance: none; }
button::-moz-focus-inner, input::-moz-focus-inner { border: 0; padding: 0; }
textarea { overflow: auto; vertical-align: top; resize: vertical; }
input:valid, textarea:valid { }
input:invalid, textarea:invalid { background-color: #f0dddd; }
table { border-collapse: collapse; border-spacing: 0; }
td { vertical-align: top; }
body
{
font-family:'Droid Sans', sans-serif;
font-size:10pt;
color:#555;
line-height: 25px;
}
.wrapper
{
width:760px;
margin:0 auto 5em auto;
}
.wrapper>header
{
border-bottom:1px solid #eee;
background-image:url(../img/logoback.png);
background-repeat:no-repeat;
background-position:right;
text-shadow:1px 1px 0px #fff;
padding-top:2.5em;
}
.wrapper>header h1
{
font-size: 28pt;
font-family: 'Ubuntu';
margin: 0 0 10px 0;
letter-spacing: 2px;
}
.wrapper>header h2
{
margin:0;
color:#888;
letter-spacing: 2px;
}
.slogan
{
font-size:0.8em;
}
.intro-text
{
width:480px;
line-height:1.4em;
}
.main
{
overflow:hidden;
}
.content
{
width:540px;
float:right;
border-left:1px solid #eee;
padding-left:1.5em;
}
.content blockquote p
{
background-color:#f8f8f8;
padding:0.5em 1em;
border-left:3px solid #E3591E;
text-shadow:1px 1px 0 #fff;
font-style:italic;
margin:3em 0;
}
.content p
{
line-height:1.6em;
margin:1.5em 0;
}
.content>h1 {
font-size: 18pt;
}
.content>h2 {
font-size: 14pt;
margin-top:2.2em;
}
.content>h3 {
font-size: 12pt;
}
.content>h4 {
font-size: 10pt;
}
.content>h1:not(:first-child) {
margin-top: 30px;
}
.content li
{
line-height:1.5em;
margin-bottom:1em;
}
a, a:visited
{
color:#2972A3;
text-decoration:none;
}
a:hover
{
color:#72ADD4;
text-decoration:underline;
}
.sidebar
{
width:180px;
float:left;
font-size:0.9em;
}
.sidebar>ul
{
list-style-type:none;
padding-left:1em;
margin:0;
padding: 0;
}
.sidebar>ul li:before
{
text-decoration:none;
color:#777;
margin-right:0.2em;
}
.sidebar>ul ul
{
list-style-type:none;
margin:0 0 0 1.5em;
padding:0;
}
.sidebar>ul ul>li:before
{
content:"\2013";
margin-right:0.4em;
}
pre, code
{
font-family: Monaco, "Bitstream Vera Sans Mono", "Lucida Console", Terminal, monospace;
}
pre
{
border:1px solid #eee;
padding:0.5em 1em;
font-size:0.8em;
background-color:#f5f5f5;
text-shadow:1px 1px 0 #fff;
line-height:1.7em;
}
code
{
background-color:#FFE5DB;
font-size:0.8em;
display:inline-block;
padding:0.2em 0.4em;
text-shadow:1px 1px 0 #fff;
}
/* Prettify Styles -------------- */
.com {
color: #93a1a1;
}
.lit {
color: #195f91;
}
.pun, .opn, .clo {
color: #93a1a1;
}
.fun {
color: #dc322f;
}
.str, .atv {
color: #D14;
}
.kwd, .linenums .tag {
color: #1e347b;
}
.typ,
.atn,
.dec,
.var {
color: teal;
}
.pln {
color: #48484c;
}
.prettyprint
{
padding:0;
text-shadow:1px 1px 0 #fff;
}
.prettyprint ol
{
color:#ccc;
}
/* end ------------------------ */
@media print {
* { background: transparent !important; color: black !important; box-shadow:none !important; text-shadow: none !important; filter:none !important; -ms-filter: none !important; }
a, a:visited { text-decoration: underline; }
a[href]:after { content: " (" attr(href) ")"; }
abbr[title]:after { content: " (" attr(title) ")"; }
.ir a:after, a[href^="javascript:"]:after, a[href^="#"]:after { content: ""; }
pre, blockquote { border: 1px solid #999; page-break-inside: avoid; }
thead { display: table-header-group; }
tr, img { page-break-inside: avoid; }
img { max-width: 100% !important; }
@page { margin: 0.5cm; }
p, h2, h3 { orphans: 3; widows: 3; }
h2, h3 { page-break-after: avoid; }
}
This diff is collapsed.
This diff is collapsed.
# 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.
This diff is collapsed.
# 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
This diff is collapsed.
This diff is collapsed.
# 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
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.
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.
This diff is collapsed.
This diff is collapsed.
*
!.gitignore
\ No newline at end of file
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