diff --git a/artisan.md b/artisan.md index ef33ab70981..9a212d4980b 100644 --- a/artisan.md +++ b/artisan.md @@ -13,24 +13,28 @@ Artisan is the name of the command-line interface included with Laravel. It prov To view a list of all available Artisan commands, you may use the `list` command: + **Listing All Available Commands** php artisan list Every command also includes a "help" screen which displays and describes the command's available arguments and options. To view a help screen, simply precede the name of the command with `help`: + **Viewing The Help Screen For A Command** php artisan help migrate You may specify the configuration environment that should be used while running a command using the `--env` switch: + **Specifying The Configuration Environment** php artisan migrate --env=local You may also view the current version of your Laravel installation using the `--version` option: + **Displaying Your Current Laravel Version** php artisan --version diff --git a/cache.md b/cache.md index 4a52ea55812..45bef96036e 100644 --- a/cache.md +++ b/cache.md @@ -9,6 +9,8 @@ ## Configuration + + Laravel provides a unified API for various caching systems. The cache configuration is located at `app/config/cache.php`. In this file you may specify which cache driver you would like used by default throughout your application. Laravel supports popular caching backends like [Memcached](http://memcached.org) and [Redis](http://redis.io) out of the box. The cache configuration file also contains various other options, which are documented within the file, so make sure to read over these options. By default, Laravel is configured to use the `file` cache driver, which stores the serialized, cached objects in the filesystem. For larger applications, it is recommended that you use an in-memory cache such as Memcached or APC. @@ -16,14 +18,17 @@ The cache configuration file also contains various other options, which are docu ## Cache Usage + **Storing An Item In The Cache** Cache::put('key', 'value', $minutes); + **Storing An Item In The Cache If It Doesn't Exist** Cache::add('key', 'value', $minutes); + **Checking For Existence In Cache** if (Cache::has('key')) @@ -31,16 +36,19 @@ The cache configuration file also contains various other options, which are docu // } + **Retrieving An Item From The Cache** $value = Cache::get('key'); + **Retrieving An Item Or Returning A Default Value** $value = Cache::get('key', 'default'); $value = Cache::get('key', function() { return 'default'; }); + **Storing An Item In The Cache Permanently** Cache::forever('key', 'value'); @@ -61,6 +69,7 @@ You may also combine the `remember` and `forever` methods: Note that all items stored in the cache are serialized, so you are free to store any type of data. + **Removing An Item From The Cache** Cache::forget('key'); @@ -70,12 +79,14 @@ Note that all items stored in the cache are serialized, so you are free to store All drivers except `file` and `database` support the `increment` and `decrement` operations: + **Incrementing A Value** Cache::increment('key'); Cache::increment('key', $amount); + **Decrementing A Value** Cache::decrement('key'); @@ -89,6 +100,7 @@ All drivers except `file` and `database` support the `increment` and `decrement` Cache sections allow you to group related items in the cache, and then flush the entire section. To access a section, use the `section` method: + **Accessing A Cache Section** Cache::section('people')->put('John', $john); @@ -97,6 +109,7 @@ Cache sections allow you to group related items in the cache, and then flush the You may also access cached items from the section, as well as use the other cache methods such as `increment` and `decrement`: + **Accessing Items In A Cache Section** $anne = Cache::section('people')->get('Anne'); diff --git a/commands.md b/commands.md index b7c992d6894..7425368379c 100644 --- a/commands.md +++ b/commands.md @@ -17,6 +17,7 @@ In addition to the commands provided with Artisan, you may also build your own c To create a new command, you may use the `command:make` Artisan command, which will generate a command stub to help you get started: + **Generate A New Command Class** php artisan command:make FooCommand @@ -59,18 +60,22 @@ The `VALUE_NONE` option indicates that the option is simply used as a "switch": While your command is executing, you will obviously need to access the values for the arguments and options accepted by your application. To do so, you may use the `argument` and `option` methods: + **Retrieving The Value Of A Command Argument** $value = $this->argument('name'); + **Retrieving All Arguments** $arguments = $this->argument(); + **Retrieving The Value Of A Command Option** $value = $this->option('name'); + **Retrieving All Options** $options = $this->option(); @@ -79,10 +84,12 @@ While your command is executing, you will obviously need to access the values fo To send output to the console, you may use the `info`, `comment`, `question` and `error` methods. Each of these methods will use the appropriate ANSI colors for their purpose. + **Sending Information To The Console** $this->info('Display this on the screen'); + **Sending An Error Message To The Console** $this->error('Something went wrong!'); @@ -91,14 +98,17 @@ To send output to the console, you may use the `info`, `comment`, `question` and You may also use the `ask` and `confirm` methods to prompt the user for input: + **Asking The User For Input** $name = $this->ask('What is your name?'); + **Asking The User For Secret Input** $password = $this->secret('What is the password?'); + **Asking The User For Confirmation** if ($this->confirm('Do you wish to continue? [yes|no]')) @@ -115,12 +125,14 @@ You may also specify a default value to the `confirm` method, which should be `t Once your command is finished, you need to register it with Artisan so it will be available for use. This is typically done in the `app/start/artisan.php` file. Within this file, you may use the `Artisan::add` method to register the command: + **Registering An Artisan Command** Artisan::add(new CustomCommand); If your command is registered in the application [IoC container](/docs/ioc), you may use the `Artisan::resolve` method to make it available to Artisan: + **Registering A Command That Is In The IoC Container** Artisan::resolve('binding.name'); @@ -130,6 +142,7 @@ If your command is registered in the application [IoC container](/docs/ioc), you Sometimes you may wish to call other commands from your command. You may do so using the `call` method: + **Calling Another Command** $this->call('command.name', array('argument' => 'foo', '--option' => 'bar')); diff --git a/configuration.md b/configuration.md index 05cc99d851c..f9655d912dc 100644 --- a/configuration.md +++ b/configuration.md @@ -11,6 +11,7 @@ All of the configuration files for the Laravel framework are stored in the `app/ Sometimes you may need to access configuration values at run-time. You may do so using the `Config` class: + **Accessing A Configuration Value** Config::get('app.timezone'); @@ -21,6 +22,7 @@ You may also specify a default value to return if the configuration option does Notice that "dot" style syntax may be used to access values in the various files. You may also set configuration values at run-time: + **Setting A Configuration Value** Config::set('database.default', 'sqlite'); @@ -63,6 +65,7 @@ You may also pass a `Closure` to the `detectEnvironment` method, allowing you to You may access the current application environment via the `environment` method: + **Accessing The Current Application Environment** $environment = App::environment(); diff --git a/controllers.md b/controllers.md index 29177e495f7..cd0011e9e10 100644 --- a/controllers.md +++ b/controllers.md @@ -99,6 +99,7 @@ You may also specify controller filters inline using a Closure: Laravel allows you to easily define a single route to handle every action in a controller using simple, REST naming conventions. First, define the route using the `Route::controller` method: + **Defining A RESTful Controller** Route::controller('users', 'UserController'); @@ -140,6 +141,7 @@ Now we can register a resourceful route to the controller: This single route declaration creates multiple routes to handle a variety of RESTful actions on the photo resource. Likewise, the generated controller will already have stubbed methods for each of these actions with notes informing you which URIs and verbs they handle. + **Actions Handled By Resource Controller** Verb | Path | Action | Route Name @@ -168,6 +170,7 @@ And, you may also specify a subset of actions to handle on the route: A catch-all method may be defined which will be called when no other matching method is found on a given controller. The method should be named `missingMethod`, and receives the parameter array for the request as its only argument: + **Defining A Catch-All Method** public function missingMethod($parameters) diff --git a/database.md b/database.md index 6898653d339..a96a35aa528 100644 --- a/database.md +++ b/database.md @@ -18,32 +18,38 @@ Currently Laravel supports four database systems: MySQL, Postgres, SQLite, and S Once you have configured your database connection, you may run queries using the `DB` class. + **Running A Select Query** $results = DB::select('select * from users where id = ?', array(1)); The `select` method will always return an `array` of results. + **Running An Insert Statement** DB::insert('insert into users (id, name) values (?, ?)', array(1, 'Dayle')); + **Running An Update Statement** DB::update('update users set votes = 100 where name = ?', array('John')); + **Running A Delete Statement** DB::delete('delete from users'); > **Note:** The `update` and `delete` statements return the number of rows affected by the operation. + **Running A General Statement** DB::statement('drop table users'); You may listen for query events using the `DB::listen` method: + **Listening For Query Events** DB::listen(function($sql, $bindings, $time) diff --git a/eloquent.md b/eloquent.md index 61294fdf539..3abd3960284 100644 --- a/eloquent.md +++ b/eloquent.md @@ -32,6 +32,7 @@ Before getting started, be sure to configure a database connection in `app/confi To get started, create an Eloquent model. Models typically live in the `app/models` directory, but you are free to place them anywhere that can be auto-loaded according to your `composer.json` file. + **Defining An Eloquent Model** class User extends Eloquent {} @@ -48,10 +49,12 @@ Note that we did not tell Eloquent which table to use for our `User` model. The Once a model is defined, you are ready to start retrieving and creating records in your table. Note that you will need to place `updated_at` and `created_at` columns on your table by default. If you do not wish to have these columns automatically maintained, set the `$timestamps` property on your model to `false`. + **Retrieving All Models** $users = User::all(); + **Retrieving A Record By Primary Key** $user = User::find(1); @@ -60,6 +63,7 @@ Once a model is defined, you are ready to start retrieving and creating records > **Note:** All methods available on the [query builder](/docs/queries) are also available when querying Eloquent models. + **Retrieving A Model By Primary Key Or Throw An Exception** Sometimes you may wish to throw an exception if a model is not found, allowing you to catch the exceptions using an `App::error` handler and display a 404 page. @@ -75,6 +79,7 @@ To register the error handler, listen for the `ModelNotFoundException` return Response::make('Not Found', 404); }); + **Querying Using Eloquent Models** $users = User::where('votes', '>', 100)->take(10)->get(); @@ -86,6 +91,7 @@ To register the error handler, listen for the `ModelNotFoundException` Of course, you may also use the query builder aggregate functions. + **Eloquent Aggregates** $count = User::where('votes', '>', 100)->count(); @@ -99,6 +105,7 @@ To get started, set the `fillable` or `guarded` properties on your model. The `fillable` property specifies which attributes should be mass-assignable. This can be set at the class or instance level. + **Defining Fillable Attributes On A Model** class User extends Eloquent { @@ -111,6 +118,7 @@ In this example, only the three listed attributes will be mass-assignable. The inverse of `fillable` is `guarded`, and serves as a "black-list" instead of a "white-list": + **Defining Guarded Attributes On A Model** class User extends Eloquent { @@ -121,6 +129,7 @@ The inverse of `fillable` is `guarded`, and serves as a "black-list" instead of In the example above, the `id` and `password` attributes may **not** be mass assigned. All other attributes will be mass assignable. You may also block **all** attributes from mass assignment using the guard method: + **Blocking All Attributes From Mass Assignment** protected $guarded = array('*'); @@ -130,6 +139,7 @@ In the example above, the `id` and `password` attributes may **not** be mass ass To create a new record in the database from a model, simply create a new model instance and call the `save` method. + **Saving A New Model** $user = new User; @@ -142,6 +152,7 @@ To create a new record in the database from a model, simply create a new model i You may also use the `create` method to save a new model in a single line. The inserted model instance will be returned to you from the method. However, before doing so, you will need to specify either a `fillable` or `guarded` attribute on the model, as all Eloquent models protect against mass-assignment. + **Setting The Guarded Attributes On The Model** class User extends Eloquent { @@ -150,12 +161,14 @@ You may also use the `create` method to save a new model in a single line. The i } + **Using The Model Create Method** $user = User::create(array('name' => 'John')); To update a model, you may retrieve it, change an attribute, and use the `save` method: + **Updating A Retrieved Model** $user = User::find(1); @@ -166,6 +179,7 @@ To update a model, you may retrieve it, change an attribute, and use the `save` Sometimes you may wish to save not only a model, but also all of its relationships. To do so, you may use the `push` method: + **Saving A Model And Relationships** $user->push(); @@ -176,12 +190,14 @@ You may also run updates as queries against a set of models: To delete a model, simply call the `delete` method on the instance: + **Deleting An Existing Model** $user = User::find(1); $user->delete(); + **Deleting An Existing Model By Key** User::destroy(1); @@ -194,6 +210,7 @@ Of course, you may also run a delete query on a set of models: If you wish to simply update the timestamps on a model, you may use the `touch` method: + **Updating Only The Model's Timestamps** $user->touch(); @@ -203,6 +220,7 @@ If you wish to simply update the timestamps on a model, you may use the `touch` By default, Eloquent will maintain the `created_at` and `updated_at` columns on your database table automatically. Simply add these `datetime` columns to your table and Eloquent will take care of the rest. If you do not wish for Eloquent to maintain these columns, add the following property to your model: + **Disabling Auto Timestamps** class User extends Eloquent { @@ -215,6 +233,7 @@ By default, Eloquent will maintain the `created_at` and `updated_at` columns on If you wish to customize the format of your timestamps, you may override the `freshTimestamp` method in your model: + **Providing A Custom Timestamp Format** class User extends Eloquent { @@ -243,6 +262,7 @@ To add a `deleted_at` column to your table, you may use the `softDeletes` method Now, when you call the `delete` method on the model, the `deleted_at` column will be set to the current timestamp. When querying a model that uses soft deletes, the "deleted" models will not be included in query results. To force soft deleted models to appear in a result set, use the `withTrashed` method on the query: + **Forcing Soft Deleted Models Into Results** $users = User::withTrashed()->where('account_id', 1)->get(); @@ -283,6 +303,7 @@ To determine if a given model instance has been soft deleted, you may use the `t Scopes allow you to easily re-use query logic in your models. To define a scope, simply prefix a model method with `scope`: + **Defining A Query Scope** class User extends Eloquent { @@ -294,6 +315,7 @@ Scopes allow you to easily re-use query logic in your models. To define a scope, } + **Utilizing A Query Scope** $users = User::popular()->orderBy('created_at')->get(); @@ -313,6 +335,7 @@ Of course, your database tables are probably related to one another. For example A one-to-one relationship is a very basic relation. For example, a `User` model might have one `Phone`. We can define this relation in Eloquent: + **Defining A One To One Relation** class User extends Eloquent { @@ -340,6 +363,7 @@ Take note that Eloquent assumes the foreign key of the relationship based on the To define the inverse of the relationship on the `Phone` model, we use the `belongsTo` method: + **Defining The Inverse Of A Relation** class Phone extends Eloquent { @@ -379,6 +403,7 @@ Again, you may override the conventional foreign key by passing a second argumen To define the inverse of the relationship on the `Comment` model, we use the `belongsTo` method: + **Defining The Inverse Of A Relation** class Comment extends Eloquent { @@ -463,6 +488,7 @@ Polymorphic relations allow a model to belong to more than one other model, on a Now, we can retrieve the photos for either a staff member or an order: + **Retrieving A Polymorphic Relation** $staff = Staff::find(1); @@ -474,6 +500,7 @@ Now, we can retrieve the photos for either a staff member or an order: However, the true "polymorphic" magic is when you access the staff or order from the `Photo` model: + **Retrieving The Owner Of A Polymorphic Relation** $photo = Photo::find(1); @@ -484,6 +511,7 @@ The `imageable` relation on the `Photo` model will return either a `Staff` or `O To help understand how this works, let's explore the database structure for a polymorphic relation: + **Polymorphic Relation Table Structure** staff @@ -507,6 +535,7 @@ The key fields to notice here are the `imageable_id` and `imageable_type` on the When accessing the records for a model, you may wish to limit your results based on the existence of a relationship. For example, you wish to pull all blog posts that have at least one comment. To do so, you may use the `has` method: + **Checking Relations When Selecting** $posts = Post::has('comments')->get(); @@ -530,7 +559,7 @@ Eloquent allows you to access your relations via dynamic properties. Eloquent wi } $phone = Phone::find(1); - + Instead of echoing the user's email like this: echo $phone->user()->first()->email; @@ -611,6 +640,7 @@ It is also possible to eagerly load related models directly from an already exis You will often need to insert new related models. For example, you may wish to insert a new comment for a post. Instead of manually setting the `post_id` foreign key on the model, you may insert the new comment from its parent `Post` model directly: + **Attaching A Related Model** $comment = new Comment(array('message' => 'A new comment.')); @@ -625,6 +655,7 @@ In this example, the `post_id` field will automatically be set on the inserted c You may also insert related models when working with many-to-many relations. Let's continue using our `User` and `Role` models as examples. We can easily attach new roles to a user using the `attach` method: + **Attaching Many To Many Models** $user = User::find(1); @@ -641,12 +672,14 @@ Of course, the opposite of `attach` is `detach`: You may also use the `sync` method to attach related models. The `sync` method accepts an array of IDs to place on the pivot table. After this operation is complete, only the IDs in the array will be on the intermediate table for the model: + **Using Sync To Attach Many To Many Models** $user->roles()->sync(array(1, 2, 3)); You may also associate other pivot table values with the given IDs: + **Adding Pivot Data When Syncing** $user->roles()->sync(array(1 => array('expires' => true))); @@ -711,6 +744,7 @@ If you want your pivot table to have automatically maintained `created_at` and ` To delete all records on the pivot table for a model, you may use the `detach` method: + **Deleting Records On A Pivot Table** User::find(1)->roles()->detach(); @@ -724,6 +758,7 @@ All multi-result sets returned by Eloquent either via the `get` method or a rela For example, we may determine if a result set contains a given primary key using the `contains` method: + **Checking If A Collection Contains A Key** $roles = User::find(1)->roles; @@ -745,6 +780,7 @@ If a collection is cast to a string, it will be returned as JSON: Eloquent collections also contain a few helpful methods for looping and filtering the items they contain: + **Iterating & Filtering Collections** $roles = $user->roles->each(function($role) @@ -757,15 +793,17 @@ Eloquent collections also contain a few helpful methods for looping and filterin }); + **Applying A Callback To Each Collection Object** $roles = User::find(1)->roles; - + $roles->each(function($role) { - // + // }); + **Sorting A Collection By A Value** $roles = $roles->sortBy(function($role) @@ -775,6 +813,7 @@ Eloquent collections also contain a few helpful methods for looping and filterin Sometimes, you may wish to return a custom Collection object with your own added methods. You may specify this on your Eloquent model by overriding the `newCollection` method: + **Returning A Custom Collection Type** class User extends Eloquent { @@ -791,6 +830,7 @@ Sometimes, you may wish to return a custom Collection object with your own added Eloquent provides a convenient way to transform your model attributes when getting or setting them. Simply define a `getFooAttribute` method on your model to declare an accessor. Keep in mind that the methods should follow camel-casing, even though your database columns are snake-case: + **Defining An Accessor** class User extends Eloquent { @@ -806,6 +846,7 @@ In the example above, the `first_name` column has an accessor. Note that the val Mutators are declared in a similar fashion: + **Defining A Mutator** class User extends Eloquent { @@ -836,6 +877,7 @@ When a column is considered a date, you may set its value to a UNIX timetamp, da Eloquent models fire several events, allowing you to hook into various points in the model's lifecycle using the following methods: `creating`, `created`, `updating`, `updated`, `saving`, `saved`, `deleting`, `deleted`. If `false` is returned from the `creating`, `updating`, or `saving` events, the action will be cancelled: + **Cancelling Save Operations Via Events** User::creating(function($user) @@ -845,6 +887,7 @@ Eloquent models fire several events, allowing you to hook into various points in Eloquent models also contain a static `boot` method, which may provide a convenient place to register your event bindings. + **Setting A Model Boot Method** class User extends Eloquent { @@ -888,6 +931,7 @@ You may register an observer instance using the `observe` method: When building JSON APIs, you may often need to convert your models and relationships to arrays or JSON. So, Eloquent includes methods for doing so. To convert a model and its loaded relationship to an array, you may use the `toArray` method: + **Converting A Model To An Array** $user = User::with('roles')->first(); @@ -900,12 +944,14 @@ Note that entire collections of models may also be converted to arrays: To convert a model to JSON, you may use the `toJson` method: + **Converting A Model To JSON** return User::find(1)->toJson(); Note that when a model or collection is cast to a string, it will be converted to JSON, meaning you can return Eloquent objects directly from your application's routes! + **Returning A Model From A Route** Route::get('users', function() @@ -915,6 +961,7 @@ Note that when a model or collection is cast to a string, it will be converted t Sometimes you may wish to limit the attributes that are included in your model's array or JSON form, such as passwords. To do so, add a `hidden` property definition to your model: + **Hiding Attributes From Array Or JSON Conversion** class User extends Eloquent { diff --git a/errors.md b/errors.md index 439e48bb1c2..6c051faf76d 100644 --- a/errors.md +++ b/errors.md @@ -88,6 +88,7 @@ Monolog has a variety of additional handlers you may use for logging. If needed, You may also register an event to catch all messages passed to the log: + **Registering A Log Listener** Log::listen(function($level, $message, $context) diff --git a/events.md b/events.md index e84e1f04cd0..ebd07ec0dc0 100644 --- a/events.md +++ b/events.md @@ -11,6 +11,7 @@ The Laravel `Event` class provides a simple observer implementation, allowing you to subscribe and listen for events in your application. + **Subscribing To An Event** Event::listen('user.login', function($user) @@ -20,12 +21,14 @@ The Laravel `Event` class provides a simple observer implementation, allowing yo $user->save(); }); + **Firing An Event** $event = Event::fire('user.login', array($user)); You may also specify a priority when subscribing to events. Listeners with higher priority will be run first, while listeners that have the same priority will be run in order of subscription. + **Subscribing To Events With Priority** Event::listen('user.login', 'LoginHandler', 10); @@ -34,6 +37,7 @@ You may also specify a priority when subscribing to events. Listeners with highe Sometimes, you may wish to stop the propagation of an event to other listeners. You may do so using by returning `false` from your listener: + **Stopping The Propagation Of An Event** Event::listen('user.login', function($event) @@ -48,6 +52,7 @@ Sometimes, you may wish to stop the propagation of an event to other listeners. When registering an event listener, you may use asterisks to specify wildcard listeners: + **Registering Wildcard Event Listeners** Event::listen('foo.*', function($param, $event) @@ -62,12 +67,14 @@ This listener will handle all events that begin with `foo.`. Note that the full In some cases, you may wish to use a class to handle an event rather than a Closure. Class event listeners will be resolved out of the [Laravel IoC container](/docs/ioc), providing you the full power of dependency injection on your listeners. + **Registering A Class Listener** Event::listen('user.login', 'LoginHandler'); By default, the `handle` method on the `LoginHandler` class will be called: + **Defining An Event Listener Class** class LoginHandler { @@ -81,6 +88,7 @@ By default, the `handle` method on the `LoginHandler` class will be called: If you do not wish to use the default `handle` method, you may specify the method that should be subscribed: + **Specifying Which Method To Subscribe** Event::listen('user.login', 'LoginHandler@onLogin'); @@ -90,10 +98,12 @@ If you do not wish to use the default `handle` method, you may specify the metho Using the `queue` and `flush` methods, you may "queue" an event for firing, but not fire it immediately: + **Registering A Queued Event** Event::queue('foo', array($user)); + **Registering An Event Flusher** Event::flusher('foo', function($user) @@ -110,6 +120,7 @@ Finally, you may run the "flusher" and flush all queued events using the `flush` Event subscribers are classes that may subscribe to multiple events from within the class itself. Subscribers should define a `subscribe` method, which will be passed an event dispatcher instance: + **Defining An Event Subscriber** class UserEventHandler { @@ -147,8 +158,9 @@ Event subscribers are classes that may subscribe to multiple events from within Once the subscriber has been defined, it may be registered with the `Event` class. + **Registering An Event Subscriber** $subscriber = new UserEventHandler; - Event::subscribe($subscriber); + Event::subscribe($subscriber); diff --git a/html.md b/html.md index 732f35ad746..e81870310ba 100644 --- a/html.md +++ b/html.md @@ -14,6 +14,7 @@ ## Opening A Form + **Opening A Form** {{ Form::open(array('url' => 'foo/bar')) }} @@ -41,10 +42,12 @@ If your form is going to accept file uploads, add a `files` option to your array Laravel provides an easy method of protecting your application from cross-site request forgeries. First, a random token is placed in your user's session. Don't sweat it, this is done automatically. The CSRF token will be added to your forms as a hidden field automatically. However, if you wish to generate the HTML for the hidden field, you may use the `token` method: + **Adding The CSRF Token To A Form** echo Form::token(); + **Attaching The CSRF Filter To A Route** Route::post('profile', array('before' => 'csrf', function() @@ -57,6 +60,7 @@ Laravel provides an easy method of protecting your application from cross-site r Often, you will want to populate a form based on the contents of a model. To do so, use the `Form::model` method: + **Opening A Model Form** echo Form::model($user, array('route' => array('user.update', $user->id))) @@ -74,10 +78,12 @@ This allows you to quickly build forms that not only bind to model values, but e ## Labels + **Generating A Label Element** echo Form::label('email', 'E-Mail Address'); + **Specifying Extra HTML Attributes** echo Form::label('email', 'E-Mail Address', array('class' => 'awesome')); @@ -87,16 +93,19 @@ This allows you to quickly build forms that not only bind to model values, but e ## Text, Text Area, Password & Hidden Fields + **Generating A Text Input** echo Form::text('username'); + **Specifying A Default Value** echo Form::text('email', 'example@gmail.com'); > **Note:** The *hidden* and *textarea* methods have the same signature as the *text* method. + **Generating A Password Input** echo Form::password('password'); @@ -104,21 +113,24 @@ This allows you to quickly build forms that not only bind to model values, but e ## Checkboxes and Radio Buttons + **Generating A Checkbox Or Radio Input** echo Form::checkbox('name', 'value'); - + echo Form::radio('name', 'value'); + **Generating A Checkbox Or Radio Input That Is Checked** echo Form::checkbox('name', 'value', true); - + echo Form::radio('name', 'value', true); ## File Input + **Generating A File Input** echo Form::file('image'); @@ -126,14 +138,17 @@ This allows you to quickly build forms that not only bind to model values, but e ## Drop-Down Lists + **Generating A Drop-Down List** echo Form::select('size', array('L' => 'Large', 'S' => 'Small')); + **Generating A Drop-Down List With Selected Default** echo Form::select('size', array('L' => 'Large', 'S' => 'Small'), 'S'); + **Generating A Grouped List** echo Form::select('animal', array( @@ -144,6 +159,7 @@ This allows you to quickly build forms that not only bind to model values, but e ## Buttons + **Generating A Submit Button** echo Form::submit('Click Me!'); @@ -155,6 +171,7 @@ This allows you to quickly build forms that not only bind to model values, but e It's easy to define your own custom Form class helpers called "macros". Here's how it works. First, simply register the macro with a given name and a Closure: + **Registering A Form Macro** Form::macro('myField', function() @@ -164,6 +181,7 @@ It's easy to define your own custom Form class helpers called "macros". Here's h Now you can call your macro using its name: + **Calling A Custom Form Macro** echo Form::myField(); diff --git a/installation.md b/installation.md index 02873cb744f..2d15b5ddb77 100644 --- a/installation.md +++ b/installation.md @@ -42,7 +42,7 @@ Laravel requires one set of permissions to be configured - folders within app/st Several of the framework directory paths are configurable. To change the location of these directories, check out the `bootstrap/paths.php` file. -> **Note:** Laravel is designed to protect your application code, and local storage by placing only files that are necessarily public in the public folder. It is recommended that you either set the public folder as your site's documentRoot (also known as a web root) or to place the contents of public into your site's root directory and place all of Laravel's other files outside the web root. +> **Note:** Laravel is designed to protect your application code, and local storage by placing only files that are necessarily public in the public folder. It is recommended that you either set the public folder as your site's documentRoot (also known as a web root) or to place the contents of public into your site's root directory and place all of Laravel's other files outside the web root. ## Pretty URLs diff --git a/ioc.md b/ioc.md index bccb5030e0c..1221a1b75ea 100644 --- a/ioc.md +++ b/ioc.md @@ -19,6 +19,7 @@ Understanding the Laravel IoC container is essential to building a powerful, lar There are two ways the IoC container can resolve dependencies: via Closure callbacks or automatic resolution. First, we'll explore Closure callbacks. First, a "type" may be bound into the container: + **Binding A Type Into The Container** App::bind('foo', function($app) @@ -26,6 +27,7 @@ There are two ways the IoC container can resolve dependencies: via Closure callb return new FooBar; }); + **Resolving A Type From The Container** $value = App::make('foo'); @@ -34,6 +36,7 @@ When the `App::make` method is called, the Closure callback is executed and the Sometimes, you may wish to bind something into the container that should only be resolved once, and the same instance should be returned on subsequent calls into the container: + **Binding A "Shared" Type Into The Container** App::singleton('foo', function() @@ -43,6 +46,7 @@ Sometimes, you may wish to bind something into the container that should only be You may also bind an existing object instance into the container using the `instance` method: + **Binding An Existing Instance Into The Container** $foo = new Foo; @@ -54,6 +58,7 @@ You may also bind an existing object instance into the container using the `inst The IoC container is powerful enough to resolve classes without any configuration at all in many scenarios. For example: + **Resolving A Class** class FooBar { @@ -73,6 +78,7 @@ When a type is not bound in the container, it will use PHP's Reflection faciliti However, in some cases, a class may depend on an interface implementation, not a "concrete type". When this is the case, the `App::bind` method must be used to inform the container which interface implementation to inject: + **Binding An Interface To An Implementation** App::bind('UserRepositoryInterface', 'DbUserRepository'); @@ -95,6 +101,7 @@ Since we have bound the `UserRepositoryInterface` to a concrete type, the `DbUse Laravel provides several opportunities to use the IoC container to increase the flexibility and testability of your application. One primary example is when resolving controllers. All controllers are resolved through the IoC container, meaning you can type-hint dependencies in a controller constructor, and they will automatically be injected. + **Type-Hinting Controller Dependencies** class OrderController extends BaseController { @@ -117,6 +124,7 @@ In this example, the `OrderRepository` class will automatically be injected into [Filters](/docs/routing#route-filters), [composers](/docs/responses#view-composers), and [event handlers](/docs/events#using-classes-as-listeners) may also be resolved out of the IoC container. When registering them, simply give the name of the class that should be used: + **Other Examples Of IoC Usage** Route::filter('foo', 'FooFilter'); @@ -134,6 +142,7 @@ In fact, most of the core Laravel components include service providers. All of t To create a service provider, simply extend the `Illuminate\Support\ServiceProvider` class and define a `register` method: + **Defining A Service Provider** use Illuminate\Support\ServiceProvider; @@ -157,6 +166,7 @@ Note that in the `register` method, the application IoC container is available t The container fires an event each time it resolves an object. You may listen to this event using the `resolving` method: + **Registering A Resolving Listener** App::resolving(function($object) diff --git a/lifecycle.md b/lifecycle.md index fce8d59dfb9..a146c8990fc 100644 --- a/lifecycle.md +++ b/lifecycle.md @@ -23,6 +23,7 @@ Of course, if you have other environments in addition to `local`, you may create You may also do pre and post request processing by registering `before`, `after`, `close`, `finish`, and `shutdown` application events: + **Registering Application Events** App::before(function() diff --git a/localization.md b/localization.md index 2bb050b9b43..0b836fdac59 100644 --- a/localization.md +++ b/localization.md @@ -24,6 +24,7 @@ Language strings are stored in files within the `app/lang` directory. Within thi Language files simply return an array of keyed strings. For example: + **Example Language File** **Changing The Default Language At Runtime** App::setLocale('es'); @@ -41,6 +43,7 @@ The default language for your application is stored in the `app/config/app.php` ## Basic Usage + **Retrieving Lines From A Language File** echo Lang::get('messages.welcome'); @@ -49,6 +52,7 @@ The first segment of the string passed to the `get` method is the name of the la > **Note**: If a language line does not exist, the key will be returned by the `get` method. + **Making Replacements In Lines** You may also define place-holders in your language lines: @@ -59,6 +63,7 @@ Then, pass a second argument of replacements to the `Lang::get` method: echo Lang::get('messages.welcome', array('name' => 'Dayle')); + **Determine If A Language File Contains A Line** if (Lang::has('messages.welcome')) diff --git a/mail.md b/mail.md index 297b7795a9c..12258758c1c 100644 --- a/mail.md +++ b/mail.md @@ -54,6 +54,7 @@ When attaching files to a message, you may also specify a MIME type and / or a d Embedding inline images into your e-mails is typically cumbersome; however, Laravel provides a convenient way to attach images to your e-mails and retrieving the appropriate CID. + **Embedding An Image In An E-Mail View** @@ -62,6 +63,7 @@ Embedding inline images into your e-mails is typically cumbersome; however, Lara + **Embedding Raw Data In An E-Mail View** @@ -77,6 +79,7 @@ Note that the `$message` variable is always passed to e-mail views by the `Mail` Since sending e-mail messages can drastically lengthen the response time of your application, many developers choose to queue e-mail messages for background sending. Laravel makes this easy using its built-in [unified queue API](/docs/queues). To queue a mail message, simply use the `queue` method on the `Mail` class: + **Queueing A Mail Message** Mail::queue('emails.welcome', $data, function($message) diff --git a/migrations.md b/migrations.md index 02faec5d15a..640fff1b29d 100644 --- a/migrations.md +++ b/migrations.md @@ -16,6 +16,7 @@ Migrations are a type of version control for your database. They allow a team to To create a migration, you may use the `migrate:make` command on the Artisan CLI: + **Creating A Migration** php artisan migrate:make create_users_table @@ -33,14 +34,17 @@ The `--table` and `--create` options may also be used to indicate the name of th ## Running Migrations + **Running All Outstanding Migrations** php artisan migrate + **Running All Outstanding Migrations For A Path** php artisan migrate --path=app/foo/migrations + **Running All Outstanding Migrations For A Package** php artisan migrate --package=vendor/package @@ -50,14 +54,17 @@ The `--table` and `--create` options may also be used to indicate the name of th ## Rolling Back Migrations + **Rollback The Last Migration Operation** php artisan migrate:rollback + **Rollback all migrations** php artisan migrate:reset + **Rollback all migrations and run them all again** php artisan migrate:refresh @@ -69,6 +76,7 @@ The `--table` and `--create` options may also be used to indicate the name of th Laravel also includes a simple way to seed your database with test data using seed classes. All seed classes are stored in `app/database/seeds`. Seed classes may have any name you wish, but probably should follow some sensible convention, such as `UserTableSeeder`, etc. By default, a `DatabaseSeeder` class is defined for you. From this class, you may use the `call` method to run other seed classes, allowing you to control the seeding order. + **Example Database Seed Class** class DatabaseSeeder extends Seeder { diff --git a/packages.md b/packages.md index 2f6ae5ff64c..64e444b7c71 100644 --- a/packages.md +++ b/packages.md @@ -28,6 +28,7 @@ All Laravel packages are distributed via [Packagist](http://packagist.org) and [ The easiest way to create a new package for use with Laravel is the `workbench` Artisan command. First, you will need to set a few options in the `app/config/workbench.php` file. In that file, you will find a `name` and `email` option. These values will be used to generate a `composer.json` file for your new package. Once you have supplied those values, you are ready to build a workbench package! + **Issuing The Workbench Artisan Command** php artisan workbench vendor/package --resources @@ -43,6 +44,7 @@ Once the provider has been registered, you are ready to start developing your pa When using the `workbench` command, your package will be setup with conventions that allow the package to integrate well with other parts of the Laravel framework: + **Basic Package Directory Structure** /src @@ -76,10 +78,12 @@ This method allows Laravel to know how to properly load the views, configuration When utilizing resources from a package, such as configuration items or views, a double-colon syntax will generally be used: + **Loading A View From A Package** return View::make('package::view.name'); + **Retrieving A Package Configuration Item** return Config::get('package::group.option'); @@ -100,6 +104,7 @@ Since your packages are in the `workbench` directory, you may be wondering how C In prior versions of Laravel, a `handles` clause was used to specify which URIs a package could respond to. However, in Laravel 4, a package may respond to any URI. To load a routes file for your package, simply `include` it from within your service provider's `boot` method. + **Including A Routes File From A Service Provider** public function boot() @@ -116,12 +121,14 @@ In prior versions of Laravel, a `handles` clause was used to specify which URIs Some packages may require configuration files. These files should be defined in the same way as typical application configuration files. And, when using the default `$this->package` method of registering resources in your service provider, may be accessed using the usual "double-colon" syntax: + **Accessing Package Configuration Files** Config::get('package::file.option'); However, if your package contains a single configuration file, you may simply name the file `config.php`. When this is done, you may access the options directly, without specifying the file name: + **Accessing Single File Package Configuration** Config::get('package::option'); @@ -130,6 +137,7 @@ However, if your package contains a single configuration file, you may simply na When other developers install your package, they may wish to override some of the configuration options. However, if they change the values in your package source code, they will be overwritten the next time Composer updates the package. Instead, the `config:publish` artisan command should be used: + **Executing The Config Publish Command** php artisan config:publish vendor/package @@ -143,16 +151,19 @@ When this command is executed, the configuration files for your application will You may easily create and run migrations for any of your packages. To create a migration for a package in the workbench, use the `--bench` option: + **Creating Migrations For Workbench Packages** php artisan migrate:make create_users_table --bench="vendor/package" + **Running Migrations For Workbench Packages** php artisan migrate --bench="vendor/package" To run migrations for a finished package that was installed via Composer into the `vendor` directory, you may use the `--package` directive: + **Running Migrations For An Installed Package** php artisan migrate --package="vendor/package" @@ -162,6 +173,7 @@ To run migrations for a finished package that was installed via Composer into th Some packages may have assets such as JavaScript, CSS, and images. However, we are unable to link to assets in the `vendor` or `workbench` directories, so we need a way to move these assets into the `public` directory of our application. The `asset:publish` command will take care of this for you: + **Moving Package Assets To Public** php artisan asset:publish diff --git a/pagination.md b/pagination.md index 4456ea422d8..b42b37814bc 100644 --- a/pagination.md +++ b/pagination.md @@ -16,12 +16,14 @@ The `pagination::slider` view will show an intelligent "range" of links based on There are several ways to paginate items. The simplest is by using the `paginate` method on the query builder or an Eloquent model. + **Paginating Database Results** $users = DB::table('users')->paginate(15); You may also paginate [Eloquent](/docs/eloquent) models: + **Paginating An Eloquent Model** $users = User::where('votes', '>', 100)->paginate(15); @@ -49,6 +51,7 @@ You may also access additional pagination information via the following methods: Sometimes you may wish to create a pagination instance manually, passing it an array of items. You may do so using the `Paginator::make` method: + **Creating A Paginator Manually** $paginator = Paginator::make($items, $totalItems, $perPage); diff --git a/queries.md b/queries.md index 82a2ec65409..f4e1b34a25c 100644 --- a/queries.md +++ b/queries.md @@ -22,6 +22,7 @@ The database query builder provides a convenient, fluent interface to creating a ## Selects + **Retrieving All Rows From A Table** $users = DB::table('users')->get(); @@ -31,16 +32,19 @@ The database query builder provides a convenient, fluent interface to creating a var_dump($user->name); } + **Retrieving A Single Row From A Table** $user = DB::table('users')->where('name', 'John')->first(); var_dump($user->name); + **Retrieving A Single Column From A Row** $name = DB::table('users')->where('name', 'John')->pluck('name'); + **Retrieving A List Of Column Values** $roles = DB::table('roles')->lists('title'); @@ -49,6 +53,7 @@ This method will return an array of role titles. You may also specify a custom k $roles = DB::table('roles')->lists('title', 'name'); + **Specifying A Select Clause** $users = DB::table('users')->select('name', 'email')->get(); @@ -57,16 +62,19 @@ This method will return an array of role titles. You may also specify a custom k $users = DB::table('users')->select('name as user_name')->get(); + **Adding A Select Clause To An Existing Query** $query = DB::table('users')->select('name'); $users = $query->addSelect('age')->get(); + **Using Where Operators** $users = DB::table('users')->where('votes', '>', 100)->get(); + **Or Statements** $users = DB::table('users') @@ -74,11 +82,13 @@ This method will return an array of role titles. You may also specify a custom k ->orWhere('name', 'John') ->get(); + **Using Where Between** $users = DB::table('users') ->whereBetween('votes', array(1, 100))->get(); + **Using Where In With An Array** $users = DB::table('users') @@ -87,11 +97,13 @@ This method will return an array of role titles. You may also specify a custom k $users = DB::table('users') ->whereNotIn('id', array(1, 2, 3))->get(); + **Using Where Null To Find Records With Unset Values** $users = DB::table('users') ->whereNull('updated_at')->get(); + **Order By, Group By, And Having** $users = DB::table('users') @@ -100,6 +112,7 @@ This method will return an array of role titles. You may also specify a custom k ->having('count', '>', 100) ->get(); + **Offset & Limit** $users = DB::table('users')->skip(10)->take(5)->get(); @@ -109,6 +122,7 @@ This method will return an array of role titles. You may also specify a custom k The query builder may also be used to write join statements. Take a look at the following examples: + **Basic Join Statement** DB::table('users') @@ -130,6 +144,7 @@ You may also specify more advanced join clauses: Sometimes you may need to create more advanced where clauses such as "where exists" or nested parameter groupings. The Laravel query builder can handle these as well: + **Parameter Grouping** DB::table('users') @@ -145,6 +160,7 @@ The query above will produce the following SQL: select * from users where name = 'John' or (votes > 100 and title <> 'Admin') + **Exists Statements** DB::table('users') @@ -168,6 +184,7 @@ The query above will produce the following SQL: The query builder also provides a variety of aggregate methods, such as `count`, `max`, `min`, `avg`, and `sum`. + **Using Aggregate Methods** $users = DB::table('users')->count(); @@ -185,6 +202,7 @@ The query builder also provides a variety of aggregate methods, such as `count`, Sometimes you may need to use a raw expression in a query. These expressions will be injected into the query as strings, so be careful not to create any SQL injection points! To create a raw expression, you may use the `DB::raw` method: + **Using A Raw Expression** $users = DB::table('users') @@ -193,6 +211,7 @@ Sometimes you may need to use a raw expression in a query. These expressions wil ->groupBy('status') ->get(); + **Incrementing or decrementing a value of a column** DB::table('users')->increment('votes'); @@ -202,6 +221,7 @@ Sometimes you may need to use a raw expression in a query. These expressions wil ## Inserts + **Inserting Records Into A Table** DB::table('users')->insert( @@ -210,6 +230,7 @@ Sometimes you may need to use a raw expression in a query. These expressions wil If the table has an auto-incrementing id, use `insertGetId` to insert a record and retrieve the id: + **Inserting Records Into A Table With An Auto-Incrementing ID** $id = DB::table('users')->insertGetId( @@ -218,6 +239,7 @@ If the table has an auto-incrementing id, use `insertGetId` to insert a record a > **Note:** When using PostgreSQL the insertGetId method expects the auto-incrementing column to be named "id". + **Inserting Multiple Records Into A Table** DB::table('users')->insert(array( @@ -228,6 +250,7 @@ If the table has an auto-incrementing id, use `insertGetId` to insert a record a ## Updates + **Updating Records In A Table** DB::table('users') @@ -237,14 +260,17 @@ If the table has an auto-incrementing id, use `insertGetId` to insert a record a ## Deletes + **Deleting Records In A Table** DB::table('users')->where('votes', '<', 100)->delete(); + **Deleting All Records From A Table** DB::table('users')->delete(); + **Truncating A Table** DB::table('users')->truncate(); @@ -254,6 +280,7 @@ If the table has an auto-incrementing id, use `insertGetId` to insert a record a The query builder also provides a quick way to "union" two queries together: + **Performing A Query Union** $first = DB::table('users')->whereNull('first_name'); @@ -267,6 +294,7 @@ The `unionAll` method is also available, and has the same method signature as `u You may easily cache the results of a query using the `remember` method: + **Caching A Query Result** $users = DB::table('users')->remember(10)->get(); diff --git a/queues.md b/queues.md index 61f89059cb8..292c4967683 100644 --- a/queues.md +++ b/queues.md @@ -24,12 +24,14 @@ The following dependencies are needed for the listed queue drivers: To push a new job onto the queue, use the `Queue::push` method: + **Pushing A Job Onto The Queue** Queue::push('SendEmail', array('message' => $message)); The first argument given to the `push` method is the name of the class that should be used to process the job. The second argument is an array of data that should be passed to the handler. A job handler should be defined like so: + **Defining A Job Handler** class SendEmail { @@ -45,12 +47,14 @@ Notice the only method that is required is `fire`, which receives a `Job` instan If you want the job to use a method other than `fire`, you may specify the method when you push the job: + **Specifying A Custom Handler Method** Queue::push('SendEmail@send', array('message' => $message)); Once you have processed a job, it must be deleted from the queue, which can be done via the `delete` method on the `Job` instance: + **Deleting A Processed Job** public function fire($job, $data) @@ -62,6 +66,7 @@ Once you have processed a job, it must be deleted from the queue, which can be d If you wish to release a job back onto the queue, you may do so via the `release` method: + **Releasing A Job Back Onto The Queue** public function fire($job, $data) @@ -77,6 +82,7 @@ You may also specify the number of seconds to wait before the job is released: If an exception occurs while the job is being processed, it will automatically be released back onto the queue. You may check the number of attempts that have been made to run the job using the `attempts` method: + **Checking The Number Of Run Attempts** if ($job->attempts() > 3) @@ -86,6 +92,7 @@ If an exception occurs while the job is being processed, it will automatically b You may also access the job identifier: + **Accessing The Job ID** $job->getJobId(); @@ -95,6 +102,7 @@ You may also access the job identifier: You may also push a Closure onto the queue. This is very convenient for quick, simple tasks that need to be queued: + **Pushing A Closure Onto The Queue** Queue::push(function($job) use ($id) @@ -113,6 +121,7 @@ When using Iron.io [push queues](#push-queues), you should take extra precaution Laravel includes an Artisan task that will run new jobs as they are pushed onto the queue. You may run this task using the `queue:listen` command: + **Starting The Queue Listener** php artisan queue:listen @@ -125,12 +134,14 @@ Note that once this task has started, it will continue to run until it is manual You may also set the length of time (in seconds) each job should be allowed to run: + **Specifying The Job Timeout Parameter** php artisan queue:listen --timeout=60 To process only the first job on the queue, you may use the `queue:work` command: + **Processing The First Job On The Queue** php artisan queue:work @@ -142,6 +153,7 @@ Push queues allow you to utilize the powerful Laravel 4 queue facilities without Next, you may use the `queue:subscribe` Artisan command to register a URL end-point that will receive newly pushed queue jobs: + **Registering A Push Queue Subscriber** php artisan queue:subscribe queue_name http://foo.com/queue/receive diff --git a/redis.md b/redis.md index a572faff126..8f1a52d1a75 100644 --- a/redis.md +++ b/redis.md @@ -67,6 +67,7 @@ When you are simply executing commands against the default connection, just use Pipelining should be used when you need to send many commands to the server in one operation. To get started, use the `pipeline` command: + **Piping Many Commands To Your Servers** Redis::pipeline(function($pipe) diff --git a/requests.md b/requests.md index 20341878db3..925b7717a38 100644 --- a/requests.md +++ b/requests.md @@ -11,14 +11,17 @@ You may access all user input with a few simple methods. You do not need to worry about the HTTP verb used for the request, as input is accessed in the same way for all verbs. + **Retrieving An Input Value** $name = Input::get('name'); + **Retrieving A Default Value If The Input Value Is Absent** $name = Input::get('name', 'Sally'); + **Determining If An Input Value Is Present** if (Input::has('name')) @@ -26,10 +29,12 @@ You may access all user input with a few simple methods. You do not need to worr // } + **Getting All Input For The Request** $input = Input::all(); + **Getting Only Some Of The Request Input** $input = Input::only('username', 'password'); @@ -43,16 +48,19 @@ Some JavaScript libraries such as Backbone may send input to the application as All cookies created by the Laravel framework are encrypted and signed with an authentication code, meaning they will be considered invalid if they have been changed by the client. + **Retrieving A Cookie Value** $value = Cookie::get('name'); + **Attaching A New Cookie To A Response** $response = Response::make('Hello World'); $response->withCookie(Cookie::make('name', 'value', $minutes)); + **Creating A Cookie That Lasts Forever** $cookie = Cookie::forever('name', 'value'); @@ -62,10 +70,12 @@ All cookies created by the Laravel framework are encrypted and signed with an au You may need to keep input from one request until the next request. For example, you may need to re-populate a form after checking it for validation errors. + **Flashing Input To The Session** Input::flash(); + **Flashing Only Some Input To The Session** Input::flashOnly('username', 'email'); @@ -80,6 +90,7 @@ Since you often will want to flash input in association with a redirect to the p > **Note:** You may flash other data across requests using the [Session](/docs/session) class. + **Retrieving Old Data** Input::old('username'); @@ -87,10 +98,12 @@ Since you often will want to flash input in association with a redirect to the p ## Files + **Retrieving An Uploaded File** $file = Input::file('photo'); + **Determining If A File Was Uploaded** if (Input::hasFile('photo')) @@ -100,20 +113,24 @@ Since you often will want to flash input in association with a redirect to the p The object returned by the `file` method is an instance of the `Symfony\Component\HttpFoundation\File\UploadedFile` class, which extends the PHP `SplFileInfo` class and provides a variety of methods for interacting with the file. + **Moving An Uploaded File** Input::file('photo')->move($destinationPath); Input::file('photo')->move($destinationPath, $fileName); + **Retrieving The Path To An Uploaded File** $path = Input::file('photo')->getRealPath(); + **Retrieving The Size Of An Uploaded File** $size = Input::file('photo')->getSize(); + **Retrieving The MIME Type Of An Uploaded File** $mime = Input::file('photo')->getMimeType(); @@ -123,10 +140,12 @@ The object returned by the `file` method is an instance of the `Symfony\Componen The `Request` class provides many methods for examining the HTTP request for your application and extends the `Symfony\Component\HttpFoundation\Request` class. Here are some of the highlights. + **Retrieving The Request URI** $uri = Request::path(); + **Determining If The Request Path Matches A Pattern** if (Request::is('admin/*')) @@ -134,22 +153,27 @@ The `Request` class provides many methods for examining the HTTP request for you // } + **Get The Request URL** $url = Request::url(); + **Retrieve A Request URI Segment** $segment = Request::segment(1); + **Retrieving A Request Header** $value = Request::header('Content-Type'); + **Retrieving Values From $_SERVER** $value = Request::server('PATH_INFO'); + **Determine If The Request Is Using AJAX** if (Request::ajax()) @@ -157,6 +181,7 @@ The `Request` class provides many methods for examining the HTTP request for you // } + **Determining If The Request Is Over HTTPS** if (Request::secure()) diff --git a/responses.md b/responses.md index 4655e4da85d..4ab762a8bb8 100644 --- a/responses.md +++ b/responses.md @@ -9,6 +9,7 @@ ## Basic Responses + **Returning Strings From Routes** Route::get('/', function() @@ -16,6 +17,7 @@ return 'Hello World'; }); + **Creating Custom Responses** A `Response` instance inherits from the `Symfony\Component\HttpFoundation\Response` class, providing a variety of methods for building HTTP responses. @@ -26,6 +28,7 @@ A `Response` instance inherits from the `Symfony\Component\HttpFoundation\Respon return $response; + **Attaching Cookies To Responses** $cookie = Cookie::make('name', 'value'); @@ -35,30 +38,37 @@ A `Response` instance inherits from the `Symfony\Component\HttpFoundation\Respon ## Redirects + **Returning A Redirect** return Redirect::to('user/login'); + **Returning A Redirect To A Named Route** return Redirect::route('login'); + **Returning A Redirect To A Named Route With Parameters** return Redirect::route('profile', array(1)); + **Returning A Redirect To A Named Route Using Named Parameters** return Redirect::route('profile', array('user' => 1)); + **Returning A Redirect To A Controller Action** return Redirect::action('HomeController@index'); + **Returning A Redirect To A Controller Action With Parameters** return Redirect::action('UserController@profile', array(1)); + **Returning A Redirect To A Controller Action Using Named Parameters** return Redirect::action('UserController@profile', array('user' => 1)); @@ -87,6 +97,7 @@ This view may be returned to the browser like so: The second argument passed to `View::make` is an array of data that should be made available to the view. + **Passing Data To Views** $view = View::make('greeting', $data); @@ -99,6 +110,7 @@ You may also share a piece of data across all views: View::share('name', 'Steve'); + **Passing A Sub-View To A View** Sometimes you may wish to pass a view into another view. For example, given a sub-view stored at `app/views/child/view.php`, we could pass it to another view like so: @@ -121,6 +133,7 @@ The sub-view can then be rendered from the parent view: View composers are callbacks or class methods that are called when a view is created. If you have data that you want bound to a given view each time that view is created throughout your application, a view composer can organize that code into a single location. Therefore, view composers may function like "view models" or "presenters". + **Defining A View Composer** View::composer('profile', function($view) @@ -157,14 +170,17 @@ Note that there is no convention on where composer classes may be stored. You ar ## Special Responses + **Creating A JSON Response** return Response::json(array('name' => 'Steve', 'state' => 'CA')); + **Creating A JSONP Response** return Response::json(array('name' => 'Steve', 'state' => 'CA'))->setCallback(Input::get('callback')); + **Creating A File Download Response** return Response::download($pathToFile); diff --git a/routing.md b/routing.md index 522e55fb578..523e50f3266 100644 --- a/routing.md +++ b/routing.md @@ -16,6 +16,7 @@ Most of the routes for your application will be defined in the `app/routes.php` file. The simplest Laravel routes consist of a URI and a Closure callback. + **Basic GET Route** Route::get('/', function() @@ -23,6 +24,7 @@ Most of the routes for your application will be defined in the `app/routes.php` return 'Hello World'; }); + **Basic POST Route** Route::post('foo/bar', function() @@ -30,6 +32,7 @@ Most of the routes for your application will be defined in the `app/routes.php` return 'Hello World'; }); + **Registering A Route Responding To Any HTTP Verb** Route::any('foo', function() @@ -37,6 +40,7 @@ Most of the routes for your application will be defined in the `app/routes.php` return 'Hello World'; }); + **Forcing A Route To Be Served Over HTTPS** Route::get('foo', array('https', function() @@ -56,6 +60,7 @@ Often, you will need to generate URLs to your routes, you may do so using the `U return 'User '.$id; }); + **Optional Route Parameters** Route::get('user/{name?}', function($name = null) @@ -63,6 +68,7 @@ Often, you will need to generate URLs to your routes, you may do so using the `U return $name; }); + **Optional Route Parameters With Defaults** Route::get('user/{name?}', function($name = 'John') @@ -70,6 +76,7 @@ Often, you will need to generate URLs to your routes, you may do so using the `U return $name; }); + **Regular Expression Route Constraints** Route::get('user/{name}', function($name) @@ -89,6 +96,7 @@ Often, you will need to generate URLs to your routes, you may do so using the `U Route filters provide a convenient way of limiting access to a given route, which is useful for creating areas of your site which require authentication. There are several filters included in the Laravel framework, including an `auth` filter, an `auth.basic` filter, a `guest` filter, and a `csrf`filter. These are located in the `app/filters.php` file. + **Defining A Route Filter** Route::filter('old', function() @@ -101,6 +109,7 @@ Route filters provide a convenient way of limiting access to a given route, whic If a response is returned from a filter, that response will be considered the response to the request and the route will not be executed, and any `after` filters on the route will also be cancelled. + **Attaching A Filter To A Route** Route::get('user', array('before' => 'old', function() @@ -108,6 +117,7 @@ If a response is returned from a filter, that response will be considered the re return 'You are over 200 years old!'; })); + **Attaching Multiple Filters To A Route** Route::get('user', array('before' => 'auth|old', function() @@ -115,6 +125,7 @@ If a response is returned from a filter, that response will be considered the re return 'You are authenticated and over 200 years old!'; })); + **Specifying Filter Parameters** Route::filter('age', function($route, $request, $value) @@ -134,6 +145,7 @@ After filters receive a `$response` as the third argument passed to the filter: // }); + **Pattern Based Filters** You may also specify that a filter applies to an entire set of routes based on their URI. @@ -151,10 +163,12 @@ You may also constrain pattern filters by HTTP verbs: Route::when('admin/*', 'admin', array('post')); + **Filter Classes** For advanced filtering, you may wish to use a class instead of a Closure. Since filter classes are resolved out of the application [IoC Container](/docs/ioc), you will be able to utilize dependency injection in these filters for greater testability. + **Defining A Filter Class** class FooFilter { @@ -166,6 +180,7 @@ For advanced filtering, you may wish to use a class instead of a Closure. Since } + **Registering A Class Based Filter** Route::filter('foo', 'FooFilter'); @@ -217,6 +232,7 @@ Sometimes you may need to apply filters to a group of routes. Instead of specify Laravel routes are also able to handle wildcard sub-domains, and pass you wildcard parameters from the domain: + **Registering Sub-Domain Routes** Route::group(array('domain' => '{account}.myapp.com'), function() @@ -233,6 +249,7 @@ Laravel routes are also able to handle wildcard sub-domains, and pass you wildca A group of routes may be prefixed by using the `prefix` option in the attributes array of a group: + **Prefixing Grouped Routes** Route::group(array('prefix' => 'admin'), function() @@ -250,6 +267,7 @@ A group of routes may be prefixed by using the `prefix` option in the attributes Model binding provides a convenient way to inject model instances into your routes. For example, instead of injecting a user's ID, you can inject the entire User model instance that matches the given ID. First, use the `Route::model` method to specify the model that should be used for a given parameter: + **Binding A Parameter To A Model** Route::model('user', 'User'); diff --git a/schema.md b/schema.md index 46e0199ae3a..bc4ae37976c 100644 --- a/schema.md +++ b/schema.md @@ -83,6 +83,7 @@ Command | Description If you are using the MySQL database, you may use the `after` method to specify the order of columns: + **Using After On MySQL** $table->string('name')->after('email'); @@ -92,6 +93,7 @@ If you are using the MySQL database, you may use the `after` method to specify t To rename a column, you may use the `renameColumn` method on the Schema builder: + **Renaming A Column** Schema::table('users', function($table) @@ -104,6 +106,7 @@ To rename a column, you may use the `renameColumn` method on the Schema builder: ## Dropping Columns + **Dropping A Column From A Database Table** Schema::table('users', function($table) @@ -111,6 +114,7 @@ To rename a column, you may use the `renameColumn` method on the Schema builder: $table->dropColumn('votes'); }); + **Dropping Multiple Columns From A Database Table** Schema::table('users', function($table) @@ -123,6 +127,7 @@ To rename a column, you may use the `renameColumn` method on the Schema builder: You may easily check for the existence of a table or column using the `hasTable` and `hasColumn` methods: + **Checking For Existence Of Table** if (Schema::hasTable('users')) @@ -130,6 +135,7 @@ You may easily check for the existence of a table or column using the `hasTable` // } + **Checking For Existence Of Columns** if (Schema::hasColumn('users', 'email')) @@ -142,6 +148,7 @@ You may easily check for the existence of a table or column using the `hasTable` The schema builder supports several types of indexes. There are two ways to add them. First, you may fluently define them on a column definition, or you may add them separately: + **Fluently Creating A Column And Index** $table->string('email')->unique(); @@ -160,6 +167,7 @@ Command | Description Laravel also provides support for adding foreign key constraints to your tables: + **Adding A Foreign Key To A Table** $table->foreign('user_id')->references('id')->on('users'); diff --git a/security.md b/security.md index 2ff1acf638b..a61d32a9afa 100644 --- a/security.md +++ b/security.md @@ -22,10 +22,12 @@ If your application is not using Eloquent, you may use the `database` authentica The Laravel `Hash` class provides secure Bcrypt hashing: + **Hashing A Password Using Bcrypt** $password = Hash::make('secret'); + **Verifying A Password Against A Hash** if (Hash::check('secret', $hashedPassword)) @@ -33,6 +35,7 @@ The Laravel `Hash` class provides secure Bcrypt hashing: // The passwords match... } + **Checking If A Password Needs To Be Rehashed** if (Hash::needsRehash($hashed)) @@ -56,6 +59,7 @@ When the `attempt` method is called, the `auth.attempt` [event](/docs/events) wi To determine if the user is already logged into your application, you may use the `check` method: + **Determining If A User Is Authenticated** if (Auth::check()) @@ -65,6 +69,7 @@ To determine if the user is already logged into your application, you may use th If you would like to provide "remember me" functionality in your application, you may pass `true` as the second argument to the `attempt` method, which will keep the user authenticated indefinitely (or until they manually logout): + **Authenticating A User And "Remembering" Them** if (Auth::attempt(array('email' => $email, 'password' => $password), true)) @@ -76,6 +81,7 @@ If you would like to provide "remember me" functionality in your application, yo You also may add extra conditions to the authenticating query: + **Authenticating A User With Conditions** if (Auth::attempt(array('email' => $email, 'password' => $password, 'active' => 1)) @@ -85,6 +91,7 @@ You also may add extra conditions to the authenticating query: Once a user is authenticated, you may access the User model / record: + **Accessing The Logged In User** $email = Auth::user()->email; @@ -95,6 +102,7 @@ To simply log a user into the application by their ID, use the `loginUsingId` me The `validate` method allows you to validate a user's credentials without actually logging them into the application: + **Validating User Credentials Without Login** if (Auth::validate($credentials)) @@ -104,6 +112,7 @@ The `validate` method allows you to validate a user's credentials without actual You may also use the `once` method to log a user into the application for a single request. No sessions or cookies will be utilized. + **Logging A User In For A Single Request** if (Auth::once($credentials)) @@ -111,6 +120,7 @@ You may also use the `once` method to log a user into the application for a sing // } + **Logging A User Out Of The Application** Auth::logout(); @@ -120,6 +130,7 @@ You may also use the `once` method to log a user into the application for a sing Route filters may be used to allow only authenticated users to access a given route. Laravel provides the `auth` filter by default, and it is defined in `app/filters.php`. + **Protecting A Route** Route::get('profile', array('before' => 'auth', function() @@ -131,10 +142,12 @@ Route filters may be used to allow only authenticated users to access a given ro Laravel provides an easy method of protecting your application from cross-site request forgeries. + **Inserting CSRF Token Into Form** + **Validate The Submitted CSRF Token** Route::post('register', array('before' => 'csrf', function() @@ -147,6 +160,7 @@ Laravel provides an easy method of protecting your application from cross-site r HTTP Basic Authentication provides a quick way to authenticate users of your application without setting up a dedicated "login" page. To get started, attach the `auth.basic` filter to your route: + **Protecting A Route With HTTP Basic** Route::get('profile', array('before' => 'auth.basic', function() @@ -160,6 +174,7 @@ By default, the `basic` filter will use the `email` column on the user record wh You may also use HTTP Basic Authentication without setting a user identifier cookie in the session, which is particularly useful for API authentication. To do so, define a filter that returns the `onceBasic` method: + **Setting Up A Stateless HTTP Basic Filter** Route::filter('basic.once', function() @@ -174,6 +189,7 @@ You may also use HTTP Basic Authentication without setting a user identifier coo Most web applications provide a way for users to reset their forgotten passwords. Rather than forcing you to re-implement this on each application, Laravel provides convenient methods for sending password reminders and performing password resets. To get started, verify that your `User` model implements the `Illuminate\Auth\Reminders\RemindableInterface` contract. Of course, the `User` model included with the framework already implements this interface. + **Implementing The RemindableInterface** class User extends Eloquent implements RemindableInterface { @@ -187,6 +203,7 @@ Most web applications provide a way for users to reset their forgotten passwords Next, a table must be created to store the password reset tokens. To generate a migration for this table, simply execute the `auth:reminders` Artisan command: + **Generating The Reminder Table Migration** php artisan auth:reminders @@ -195,6 +212,7 @@ Next, a table must be created to store the password reset tokens. To generate a To send a password reminder, we can use the `Password::remind` method: + **Sending A Password Reminder** Route::post('password/remind', function() @@ -271,18 +289,21 @@ Also, similarly to the `remind` method, if an error occurs while resetting the p Laravel provides facilities for strong AES-256 encryption via the mcrypt PHP extension: + **Encrypting A Value** $encrypted = Crypt::encrypt('secret'); > **Note:** Be sure to set a 32 character, random string in the `key` option of the `app/config/app.php` file. Otherwise, encrypted values will not be secure. + **Decrypting A Value** $decrypted = Crypt::decrypt($encryptedValue); You may also set the cipher and mode used by the encrypter: + **Setting The Cipher & Mode** Crypt::setMode('crt'); diff --git a/session.md b/session.md index 64cd7e40a8e..54deb147878 100644 --- a/session.md +++ b/session.md @@ -15,20 +15,24 @@ The session configuration is stored in `app/config/session.php`. Be sure to revi ## Session Usage + **Storing An Item In The Session** Session::put('key', 'value'); + **Retrieving An Item From The Session** $value = Session::get('key'); + **Retrieving An Item Or Returning A Default Value** $value = Session::get('key', 'default'); $value = Session::get('key', function() { return 'default'; }); + **Determining If An Item Exists In The Session** if (Session::has('users')) @@ -36,14 +40,17 @@ The session configuration is stored in `app/config/session.php`. Be sure to revi // } + **Removing An Item From The Session** Session::forget('key'); + **Removing All Items From The Session** Session::flush(); + **Regenerating The Session ID** Session::regenerate(); @@ -55,10 +62,12 @@ Sometimes you may wish to store items in the session only for the next request. Session::flash('key', 'value'); + **Reflashing The Current Flash Data For Another Request** Session::reflash(); + **Reflashing Only A Subset Of Flash Data** Session::keep(array('username', 'email')); diff --git a/templates.md b/templates.md index b89a828312d..c6af0214416 100644 --- a/templates.md +++ b/templates.md @@ -9,6 +9,7 @@ One method of using templates in Laravel is via controller layouts. By specifying the `layout` property on the controller, the view specified will be created for you and will be the assumed response that should be returned from actions. + **Defining A Layout On A Controller** class UserController extends BaseController { @@ -33,6 +34,7 @@ One method of using templates in Laravel is via controller layouts. By specifyin Blade is a simple, yet powerful templating engine provided with Laravel. Unlike controller layouts, Blade is driven by _template inheritance_ and _sections_. All Blade templates should use the `.blade.php` extension. + **Defining A Blade Layout** @@ -49,6 +51,7 @@ Blade is a simple, yet powerful templating engine provided with Laravel. Unlike + **Using A Blade Layout** @extends('layouts.master') @@ -68,6 +71,7 @@ Note that views which `extend` a Blade layout simply override sections from the ## Other Blade Control Structures + **Echoing Data** Hello, {{ $name }}. @@ -78,6 +82,7 @@ To escape the output, you may use the triple curly brace syntax: Hello, {{{ $name }}}. + **If Statements** @if (count($records) === 1) @@ -92,6 +97,7 @@ To escape the output, you may use the triple curly brace syntax: You are not signed in. @endunless + **Loops** @for ($i = 0; $i < 10; $i++) @@ -106,16 +112,19 @@ To escape the output, you may use the triple curly brace syntax:

I'm looping forever.

@endwhile + **Including Sub-Views** @include('view.name') + **Displaying Language Lines** @lang('language.line') @choice('language.line', 1); + **Comments** {{-- This comment will not be in the rendered HTML --}} diff --git a/testing.md b/testing.md index 0a5d1ee1056..8c16f1363af 100644 --- a/testing.md +++ b/testing.md @@ -20,6 +20,7 @@ An example test file is provided in the `app/tests` directory. After installing To create a test case, simply create a new test file in the `app/tests` directory. The test class should extend `TestCase`. You may then define test methods as you normally would when using PHPUnit. + **An Example Test Class** class FooTest extends TestCase { @@ -45,6 +46,7 @@ When running unit tests, Laravel will automatically set the configuration enviro You may easily call one of your routes for a test using the `call` method: + **Calling A Route From A Test** $response = $this->call('GET', 'user/profile'); @@ -57,6 +59,7 @@ You may then inspect the `Illuminate\Http\Response` object: You may also call a controller from a test: + **Calling A Controller From A Test** $response = $this->action('GET', 'HomeController@index'); @@ -99,6 +102,7 @@ When testing, you may often want to mock a call to a Laravel static facade. For We can mock the call to the `Event` class by using the `shouldReceive` method on the facade, which will return an instance of a [Mockery](https://github.com/padraic/mockery) mock. + **Mocking A Facade** public function testGetIndex() @@ -115,6 +119,7 @@ We can mock the call to the `Event` class by using the `shouldReceive` method on Laravel ships with several `assert` methods to make testing a little easier: + **Asserting Responses Are OK** public function testMethod() @@ -124,10 +129,12 @@ Laravel ships with several `assert` methods to make testing a little easier: $this->assertResponseOk(); } + **Asserting Response Statuses** $this->assertResponseStatus(403); + **Asserting Responses Are Redirects** $this->assertRedirectedTo('foo'); @@ -136,6 +143,7 @@ Laravel ships with several `assert` methods to make testing a little easier: $this->assertRedirectedToAction('Controller@method'); + **Asserting A View Has Some Data** public function testMethod() @@ -146,6 +154,7 @@ Laravel ships with several `assert` methods to make testing a little easier: $this->assertViewHas('age', $value); } + **Asserting The Session Has Some Data** public function testMethod() @@ -163,6 +172,7 @@ The `TestCase` class contains several helper methods to make testing your applic You may set the currently authenticated user using the `be` method: + **Setting The Currently Authenticated User** $user = new User(array('name' => 'John')); @@ -171,6 +181,7 @@ You may set the currently authenticated user using the `be` method: You may re-seed your database from a test using the `seed` method: + **Re-Seeding Database From Tests** $this->seed(); diff --git a/validation.md b/validation.md index 6898ba36ffb..ebe63c8176c 100644 --- a/validation.md +++ b/validation.md @@ -12,6 +12,7 @@ Laravel ships with a simple, convenient facility for validating data and retrieving validation error messages via the `Validation` class. + **Basic Validation Example** $validator = Validator::make( @@ -23,6 +24,7 @@ The first argument passed to the `make` method is the data under validation. The Multiple rules may be delimited using either a "pipe" character, or as separate elements of an array. + **Using Arrays To Specify Rules** $validator = Validator::make( @@ -45,6 +47,7 @@ You may also access an array of the failed validation rules, without messages. T $failed = $validator->failed(); + **Validating Files** The `Validator` class provides several rules for validating files, such as `size`, `mimes`, and others. When validating files, you may simply pass them into the validator with your other data. @@ -54,10 +57,12 @@ The `Validator` class provides several rules for validating files, such as `size After calling the `messages` method on a `Validator` instance, you will receive a `MessageBag` instance, which has a variety of convenient methods for working with error messages. + **Retrieving The First Error Message For A Field** echo $messages->first('email'); + **Retrieving All Error Messages For A Field** foreach ($messages->get('email') as $message) @@ -65,6 +70,7 @@ After calling the `messages` method on a `Validator` instance, you will receive // } + **Retrieving All Error Messages For All Fields** foreach ($messages->all() as $message) @@ -72,6 +78,7 @@ After calling the `messages` method on a `Validator` instance, you will receive // } + **Determining If Messages Exist For A Field** if ($messages->has('email')) @@ -79,12 +86,14 @@ After calling the `messages` method on a `Validator` instance, you will receive // } + **Retrieving An Error Message With A Format** echo $messages->first('email', '

:message

'); > **Note:** By default, messages are formatted using Bootstrap compatible syntax. + **Retrieving All Error Messages With A Format** foreach ($messages->all('
  • :message
  • ') as $message) @@ -229,10 +238,12 @@ The field under validation must be formatted as an e-mail address. The field under validation must exists on a given database table. + **Basic Usage Of Exists Rule** 'state' => 'exists:states' + **Specifying A Custom Column Name** 'state' => 'exists:states,abbreviation' @@ -271,6 +282,7 @@ The field under validation must be less than a maximum _value_. Strings, numeric The file under validation must have a MIME type corresponding to one of the listed extensions. + **Basic Usage Of MIME Rule** 'photo' => 'mimes:jpeg,bmp,png' @@ -327,14 +339,17 @@ The field under validation must have a size matching the given _value_. For stri The field under validation must be unique on a given database table. If the `column` option is not specified, the field name will be used. + **Basic Usage Of Unique Rule** 'email' => 'unique:users' + **Specifying A Custom Column Name** 'email' => 'unique:users,email_address' + **Forcing A Unique Rule To Ignore A Given ID** 'email' => 'unique:users,email_address,10' @@ -349,6 +364,7 @@ The field under validation must be formatted as an URL. If needed, you may use custom error messages for validation instead of the defaults. There are several ways to specify custom messages. + **Passing Custom Messages Into Validator** $messages = array( @@ -359,6 +375,7 @@ If needed, you may use custom error messages for validation instead of the defau *Note:* The `:attribute` place-holder will be replaced by the actual name of the field under validation. You may also utilize other place-holders in validation messages. + **Other Validation Place-Holders** $messages = array( @@ -370,6 +387,7 @@ If needed, you may use custom error messages for validation instead of the defau Sometimes you may wish to specify a custom error messages only for a specific field: + **Specifying A Custom Message For A Given Attribute** $messages = array( @@ -378,6 +396,7 @@ Sometimes you may wish to specify a custom error messages only for a specific fi In some cases, you may wish to specify your custom messages in a language file instead of passing them directly to the `Validator`. To do so, add your messages to `custom` array in the `app/lang/xx/validation.php` language file. + **Specifying Custom Messages In Language Files** 'custom' => array( @@ -391,6 +410,7 @@ In some cases, you may wish to specify your custom messages in a language file i Laravel provides a variety of helpful validation rules; however, you may wish to specify some of your own. One method of registering custom validation rules is using the `Validator::extend` method: + **Registering A Custom Validation Rule** Validator::extend('foo', function($attribute, $value, $parameters) @@ -410,6 +430,7 @@ Note that you will also need to define an error message for your custom rules. Y Instead of using Closure callbacks to extend the Validator, you may also extend the Validator class itself. To do so, write a Validator class that extends `Illuminate\Validation\Validator`. You may add validation methods to the class by prefixing them with `validate`: + **Extending The Validator Class** **Registering A Custom Validator Resolver** Validator::resolver(function($translator, $data, $rules, $messages)