├── artisan.md
├── authentication.md
├── authorization.md
├── billing.md
├── blade.md
├── cache.md
├── collections.md
├── container.md
├── contracts.md
├── contributing.md
├── contributions.md
├── controllers.md
├── database.md
├── documentation.md
├── elixir.md
├── eloquent-collections.md
├── eloquent-mutators.md
├── eloquent-relationships.md
├── eloquent-serialization.md
├── eloquent.md
├── encryption.md
├── envoy.md
├── errors.md
├── events.md
├── facades.md
├── filesystem.md
├── hashing.md
├── helpers.md
├── homestead.md
├── installation.md
├── license.md
├── lifecycle.md
├── localization.md
├── mail.md
├── middleware.md
├── migrations.md
├── packages.md
├── pagination.md
├── providers.md
├── queries.md
├── queues.md
├── quickstart-intermediate.md
├── quickstart.md
├── readme.md
├── redis.md
├── releases.md
├── requests.md
├── responses.md
├── routing.md
├── scheduling.md
├── seeding.md
├── session.md
├── structure.md
├── testing.md
├── upgrade.md
├── validation.md
└── views.md
/blade.md:
--------------------------------------------------------------------------------
1 | # Blade Templates
2 |
3 | - [Introduction](#introduction)
4 | - [Template Inheritance](#template-inheritance)
5 | - [Defining A Layout](#defining-a-layout)
6 | - [Extending A Layout](#extending-a-layout)
7 | - [Displaying Data](#displaying-data)
8 | - [Control Structures](#control-structures)
9 | - [Service Injection](#service-injection)
10 | - [Extending Blade](#extending-blade)
11 |
12 |
13 | ## Introduction
14 |
15 | Blade is the simple, yet powerful templating engine provided with Laravel. Unlike other popular PHP templating engines, Blade does not restrict you from using plain PHP code in your views. All Blade views are compiled into plain PHP code and cached until they are modified, meaning Blade adds essentially zero overhead to your application. Blade view files use the `.blade.php` file extension and are typically stored in the `resources/views` directory.
16 |
17 |
18 | ## Template Inheritance
19 |
20 |
21 | ### Defining A Layout
22 |
23 | Two of the primary benefits of using Blade are _template inheritance_ and _sections_. To get started, let's take a look at a simple example. First, we will examine a "master" page layout. Since most web applications maintain the same general layout across various pages, it's convenient to define this layout as a single Blade view:
24 |
25 |
26 |
27 |
28 |
29 | App Name - @yield('title')
30 |
31 |
32 | @section('sidebar')
33 | This is the master sidebar.
34 | @show
35 |
36 |
37 | @yield('content')
38 |
39 |
40 |
41 |
42 | As you can see, this file contains typical HTML mark-up. However, take note of the `@section` and `@yield` directives. The `@section` directive, as the name implies, defines a section of content, while the `@yield` directive is used to display the contents of a given section.
43 |
44 | Now that we have defined a layout for our application, let's define a child page that inherits the layout.
45 |
46 |
47 | ### Extending A Layout
48 |
49 | When defining a child page, you may use the Blade `@extends` directive to specify which layout the child page should "inherit". Views which `@extends` a Blade layout may inject content into the layout's sections using `@section` directives. Remember, as seen in the example above, the contents of these sections will be displayed in the layout using `@yield`:
50 |
51 |
52 |
53 | @extends('layouts.master')
54 |
55 | @section('title', 'Page Title')
56 |
57 | @section('sidebar')
58 | @@parent
59 |
60 | This is appended to the master sidebar.
61 | @endsection
62 |
63 | @section('content')
64 | This is my body content.
65 | @endsection
66 |
67 | In this example, the `sidebar` section is utilizing the `@@parent` directive to append (rather than overwriting) content to the layout's sidebar. The `@@parent` directive will be replaced by the content of the layout when the view is rendered.
68 |
69 | Of course, just like plain PHP views, Blade views may be returned from routes using the global `view` helper function:
70 |
71 | Route::get('blade', function () {
72 | return view('child');
73 | });
74 |
75 |
76 | ## Displaying Data
77 |
78 | You may display data passed to your Blade views by wrapping the variable in "curly" braces. For example, given the following route:
79 |
80 | Route::get('greeting', function () {
81 | return view('welcome', ['name' => 'Samantha']);
82 | });
83 |
84 | You may display the contents of the `name` variable like so:
85 |
86 | Hello, {{ $name }}.
87 |
88 | Of course, you are not limited to displaying the contents of the variables passed to the view. You may also echo the results of any PHP function. In fact, you can put any PHP code you wish inside of a Blade echo statement:
89 |
90 | The current UNIX timestamp is {{ time() }}.
91 |
92 | > **Note:** Blade `{{ }}` statements are automatically sent through PHP's `htmlentities` function to prevent XSS attacks.
93 |
94 | #### Blade & JavaScript Frameworks
95 |
96 | Since many JavaScript frameworks also use "curly" braces to indicate a given expression should be displayed in the browser, you may use the `@` symbol to inform the Blade rendering engine an expression should remain untouched. For example:
97 |
98 | Laravel
99 |
100 | Hello, @{{ name }}.
101 |
102 | In this example, the `@` symbol will be removed by Blade; however, `{{ name }}` expression will remain untouched by the Blade engine, allowing it to instead be rendered by your JavaScript framework.
103 |
104 | #### Echoing Data If It Exists
105 |
106 | Sometimes you may wish to echo a variable, but you aren't sure if the variable has been set. We can express this in verbose PHP code like so:
107 |
108 | {{ isset($name) ? $name : 'Default' }}
109 |
110 | However, instead of writing a ternary statement, Blade provides you with the following convenient short-cut:
111 |
112 | {{ $name or 'Default' }}
113 |
114 | In this example, if the `$name` variable exists, its value will be displayed. However, if it does not exist, the word `Default` will be displayed.
115 |
116 | #### Displaying Unescaped Data
117 |
118 | By default, Blade `{{ }}` statements are automatically sent through PHP's `htmlentities` function to prevent XSS attacks. If you do not want your data to be escaped, you may use the following syntax:
119 |
120 | Hello, {!! $name !!}.
121 |
122 | > **Note:** Be very careful when echoing content that is supplied by users of your application. Always use the double curly brace syntax to escape any HTML entities in the content.
123 |
124 |
125 | ## Control Structures
126 |
127 | In addition to template inheritance and displaying data, Blade also provides convenient short-cuts for common PHP control structures, such as conditional statements and loops. These short-cuts provide a very clean, terse way of working with PHP control structures, while also remaining familiar to their PHP counterparts.
128 |
129 | #### If Statements
130 |
131 | You may construct `if` statements using the `@if`, `@elseif`, `@else`, and `@endif` directives. These directives function identically to their PHP counterparts:
132 |
133 | @if (count($records) === 1)
134 | I have one record!
135 | @elseif (count($records) > 1)
136 | I have multiple records!
137 | @else
138 | I don't have any records!
139 | @endif
140 |
141 | For convenience, Blade also provides an `@unless` directive:
142 |
143 | @unless (Auth::check())
144 | You are not signed in.
145 | @endunless
146 |
147 | #### Loops
148 |
149 | In addition to conditional statements, Blade provides simple directives for working with PHP's supported loop structures. Again, each of these directives functions identically to their PHP counterparts:
150 |
151 | @for ($i = 0; $i < 10; $i++)
152 | The current value is {{ $i }}
153 | @endfor
154 |
155 | @foreach ($users as $user)
156 | This is user {{ $user->id }}
157 | @endforeach
158 |
159 | @forelse ($users as $user)
160 | {{ $user->name }}
161 | @empty
162 | No users
163 | @endforelse
164 |
165 | @while (true)
166 | I'm looping forever.
167 | @endwhile
168 |
169 | #### Including Sub-Views
170 |
171 | Blade's `@include` directive, allows you to easily include a Blade view from within an existing view. All variables that are available to the parent view will be made available to the included view:
172 |
173 |
174 | @include('shared.errors')
175 |
176 |
179 |
180 |
181 | Even though the included view will inherit all data available in the parent view, you may also pass an array of extra data to the included view:
182 |
183 | @include('view.name', ['some' => 'data'])
184 |
185 | > **Note:** You should avoid using the `__DIR__` and `__FILE__` constants in your Blade views, since they will refer to the location of the cached view.
186 |
187 | #### Rendering Views For Collections
188 |
189 | You may combine loops and includes into one line with Blade's `@each` directive:
190 |
191 | @each('view.name', $jobs, 'job')
192 |
193 | The first argument is the view partial to render for each element in the array or collection. The second argument is the array or collection you wish to iterate over, while the third argument is the variable name that will be assigned to the current iteration within the view. So, for example, if you are iterating over an array of `jobs`, typically you will want to access each job as a `job` variable within your view partial.
194 |
195 | You may also pass a fourth argument to the `@each` directive. This argument determines the view that will be rendered if the given array is empty.
196 |
197 | @each('view.name', $jobs, 'job', 'view.empty')
198 |
199 | #### Comments
200 |
201 | Blade also allows you to define comments in your views. However, unlike HTML comments, Blade comments are not included in the HTML returned by your application:
202 |
203 | {{-- This comment will not be present in the rendered HTML --}}
204 |
205 |
206 | ## Service Injection
207 |
208 | The `@inject` directive may be used to retrieve a service from the Laravel [service container](/{{version}}/container). The first argument passed to `@inject` is the name of the variable the service will be placed into, while the second argument is the class / interface name of the service you wish to resolve:
209 |
210 | @inject('metrics', 'App\Services\MetricsService')
211 |
212 |
213 | Monthly Revenue: {{ $metrics->monthlyRevenue() }}.
214 |
215 |
216 |
217 | ## Extending Blade
218 |
219 | Blade even allows you to define your own custom directives. You can use the `directive` method to register a directive. When the Blade compiler encounters the directive, it calls the provided callback with its parameter.
220 |
221 | The following example creates a `@datetime($var)` directive which formats a given `$var`:
222 |
223 | format('m/d/Y H:i'); ?>";
241 | });
242 | }
243 |
244 | /**
245 | * Register bindings in the container.
246 | *
247 | * @return void
248 | */
249 | public function register()
250 | {
251 | //
252 | }
253 | }
254 |
255 | As you can see, Laravel's `with` helper function was used in this directive. The `with` helper simply returns the object / value it is given, allowing for convenient method chaining. The final PHP generated by this directive will be:
256 |
257 | format('m/d/Y H:i'); ?>
258 |
259 |
--------------------------------------------------------------------------------
/container.md:
--------------------------------------------------------------------------------
1 | # Service Container
2 |
3 | - [Introduction](#introduction)
4 | - [Binding](#binding)
5 | - [Binding Interfaces To Implementations](#binding-interfaces-to-implementations)
6 | - [Contextual Binding](#contextual-binding)
7 | - [Tagging](#tagging)
8 | - [Resolving](#resolving)
9 | - [Container Events](#container-events)
10 |
11 |
12 | ## Introduction
13 |
14 | The Laravel service container is a powerful tool for managing class dependencies and performing dependency injection. Dependency injection is a fancy phrase that essentially means this: class dependencies are "injected" into the class via the constructor or, in some cases, "setter" methods.
15 |
16 | Let's look at a simple example:
17 |
18 | mailer = $mailer;
42 | }
43 |
44 | /**
45 | * Purchase a podcast.
46 | *
47 | * @return void
48 | */
49 | public function handle()
50 | {
51 | //
52 | }
53 | }
54 |
55 | In this example, the `PurchasePodcast` job needs to send e-mails when a podcast is purchased. So, we will **inject** a service that is able to send e-mails. Since the service is injected, we are able to easily swap it out with another implementation. We are also able to easily "mock", or create a dummy implementation of the mailer when testing our application.
56 |
57 | A deep understanding of the Laravel service container is essential to building a powerful, large application, as well as for contributing to the Laravel core itself.
58 |
59 |
60 | ## Binding
61 |
62 | Almost all of your service container bindings will be registered within [service providers](/{{version}}/providers), so all of these examples will demonstrate using the container in that context. However, there is no need to bind classes into the container if they do not depend on any interfaces. The container does not need to be instructed on how to build these objects, since it can automatically resolve such "concrete" objects using PHP's reflection services.
63 |
64 | Within a service provider, you always have access to the container via the `$this->app` instance variable. We can register a binding using the `bind` method, passing the class or interface name that we wish to register along with a `Closure` that returns an instance of the class:
65 |
66 | $this->app->bind('HelpSpot\API', function ($app) {
67 | return new HelpSpot\API($app['HttpClient']);
68 | });
69 |
70 | Notice that we receive the container itself as an argument to the resolver. We can then use the container to resolve sub-dependencies of the object we are building.
71 |
72 | #### Binding A Singleton
73 |
74 | The `singleton` method binds a class or interface into the container that should only be resolved one time, and then that same instance will be returned on subsequent calls into the container:
75 |
76 | $this->app->singleton('FooBar', function ($app) {
77 | return new FooBar($app['SomethingElse']);
78 | });
79 |
80 | #### Binding Instances
81 |
82 | You may also bind an existing object instance into the container using the `instance` method. The given instance will always be returned on subsequent calls into the container:
83 |
84 | $fooBar = new FooBar(new SomethingElse);
85 |
86 | $this->app->instance('FooBar', $fooBar);
87 |
88 |
89 | ### Binding Interfaces To Implementations
90 |
91 | A very powerful feature of the service container is its ability to bind an interface to a given implementation. For example, let's assume we have an `EventPusher` interface and a `RedisEventPusher` implementation. Once we have coded our `RedisEventPusher` implementation of this interface, we can register it with the service container like so:
92 |
93 | $this->app->bind('App\Contracts\EventPusher', 'App\Services\RedisEventPusher');
94 |
95 | This tells the container that it should inject the `RedisEventPusher` when a class needs an implementation of `EventPusher`. Now we can type-hint the `EventPusher` interface in a constructor, or any other location where dependencies are injected by the service container:
96 |
97 | use App\Contracts\EventPusher;
98 |
99 | /**
100 | * Create a new class instance.
101 | *
102 | * @param EventPusher $pusher
103 | * @return void
104 | */
105 | public function __construct(EventPusher $pusher)
106 | {
107 | $this->pusher = $pusher;
108 | }
109 |
110 |
111 | ### Contextual Binding
112 |
113 | Sometimes you may have two classes that utilize the same interface, but you wish to inject different implementations into each class. For example, when our system receives a new Order, we may want to send an event via [PubNub](http://www.pubnub.com/) rather than Pusher. Laravel provides a simple, fluent interface for defining this behavior:
114 |
115 | $this->app->when('App\Handlers\Commands\CreateOrderHandler')
116 | ->needs('App\Contracts\EventPusher')
117 | ->give('App\Services\PubNubEventPusher');
118 |
119 | You may even pass a Closure to the `give` method:
120 |
121 | $this->app->when('App\Handlers\Commands\CreateOrderHandler')
122 | ->needs('App\Contracts\EventPusher')
123 | ->give(function () {
124 | // Resolve dependency...
125 | });
126 |
127 |
128 | ### Tagging
129 |
130 | Occasionally, you may need to resolve all of a certain "category" of binding. For example, perhaps you are building a report aggregator that receives an array of many different `Report` interface implementations. After registering the `Report` implementations, you can assign them a tag using the `tag` method:
131 |
132 | $this->app->bind('SpeedReport', function () {
133 | //
134 | });
135 |
136 | $this->app->bind('MemoryReport', function () {
137 | //
138 | });
139 |
140 | $this->app->tag(['SpeedReport', 'MemoryReport'], 'reports');
141 |
142 | Once the services have been tagged, you may easily resolve them all via the `tagged` method:
143 |
144 | $this->app->bind('ReportAggregator', function ($app) {
145 | return new ReportAggregator($app->tagged('reports'));
146 | });
147 |
148 |
149 | ## Resolving
150 |
151 | There are several ways to resolve something out of the container. First, you may use the `make` method, which accepts the name of the class or interface you wish to resolve:
152 |
153 | $fooBar = $this->app->make('FooBar');
154 |
155 | Secondly, you may access the container like an array, since it implements PHP's `ArrayAccess` interface:
156 |
157 | $fooBar = $this->app['FooBar'];
158 |
159 | Lastly, but most importantly, you may simply "type-hint" the dependency in the constructor of a class that is resolved by the container, including [controllers](/{{version}}/controllers), [event listeners](/{{version}}/events), [queue jobs](/{{version}}/queues), [middleware](/{{version}}/middleware), and more. In practice, this is how most of your objects are resolved by the container.
160 |
161 | The container will automatically inject dependencies for the classes it resolves. For example, you may type-hint a repository defined by your application in a controller's constructor. The repository will automatically be resolved and injected into the class:
162 |
163 | users = $users;
186 | }
187 |
188 | /**
189 | * Show the user with the given ID.
190 | *
191 | * @param int $id
192 | * @return Response
193 | */
194 | public function show($id)
195 | {
196 | //
197 | }
198 | }
199 |
200 |
201 | ## Container Events
202 |
203 | The service container fires an event each time it resolves an object. You may listen to this event using the `resolving` method:
204 |
205 | $this->app->resolving(function ($object, $app) {
206 | // Called when container resolves object of any type...
207 | });
208 |
209 | $this->app->resolving(FooBar::class, function (FooBar $fooBar, $app) {
210 | // Called when container resolves objects of type "FooBar"...
211 | });
212 |
213 | As you can see, the object being resolved will be passed to the callback, allowing you to set any additional properties on the object before it is given to its consumer.
--------------------------------------------------------------------------------
/contracts.md:
--------------------------------------------------------------------------------
1 | # Contracts
2 |
3 | - [Introduction](#introduction)
4 | - [Why Contracts?](#why-contracts)
5 | - [Contract Reference](#contract-reference)
6 | - [How To Use Contracts](#how-to-use-contracts)
7 |
8 |
9 | ## Introduction
10 |
11 | Laravel's Contracts are a set of interfaces that define the core services provided by the framework. For example, a `Illuminate\Contracts\Queue\Queue` contract defines the methods needed for queueing jobs, while the `Illuminate\Contracts\Mail\Mailer` contract defines the methods needed for sending e-mail.
12 |
13 | Each contract has a corresponding implementation provided by the framework. For example, Laravel provides a queue implementation with a variety of drivers, and a mailer implementation that is powered by [SwiftMailer](http://swiftmailer.org/).
14 |
15 | All of the Laravel contracts live in [their own GitHub repository](https://github.com/illuminate/contracts). This provides a quick reference point for all available contracts, as well as a single, decoupled package that may be utilized by package developers.
16 |
17 | ### Contracts Vs. Facades
18 |
19 | Laravel's [facades](/{{version}}/facades) provide a simple way of utilizing Laravel's services without needing to type-hint and resolve contracts out of the service container. However, using contracts allows you to define explicit dependencies for your classes. For most applications, using a facade is just fine. However, if you really need the extra loose coupling that contracts can provide, keep reading!
20 |
21 |
22 | ## Why Contracts?
23 |
24 | You may have several questions regarding contracts. Why use interfaces at all? Isn't using interfaces more complicated? Let's distil the reasons for using interfaces to the following headings: loose coupling and simplicity.
25 |
26 | ### Loose Coupling
27 |
28 | First, let's review some code that is tightly coupled to a cache implementation. Consider the following:
29 |
30 | cache = $cache;
50 | }
51 |
52 | /**
53 | * Retrieve an Order by ID.
54 | *
55 | * @param int $id
56 | * @return Order
57 | */
58 | public function find($id)
59 | {
60 | if ($this->cache->has($id)) {
61 | //
62 | }
63 | }
64 | }
65 |
66 | In this class, the code is tightly coupled to a given cache implementation. It is tightly coupled because we are depending on a concrete Cache class from a package vendor. If the API of that package changes our code must change as well.
67 |
68 | Likewise, if we want to replace our underlying cache technology (Memcached) with another technology (Redis), we again will have to modify our repository. Our repository should not have so much knowledge regarding who is providing them data or how they are providing it.
69 |
70 | **Instead of this approach, we can improve our code by depending on a simple, vendor agnostic interface:**
71 |
72 | cache = $cache;
94 | }
95 | }
96 |
97 | Now the code is not coupled to any specific vendor, or even Laravel. Since the contracts package contains no implementation and no dependencies, you may easily write an alternative implementation of any given contract, allowing you to replace your cache implementation without modifying any of your cache consuming code.
98 |
99 | ### Simplicity
100 |
101 | When all of Laravel's services are neatly defined within simple interfaces, it is very easy to determine the functionality offered by a given service. **The contracts serve as succinct documentation to the framework's features.**
102 |
103 | In addition, when you depend on simple interfaces, your code is easier to understand and maintain. Rather than tracking down which methods are available to you within a large, complicated class, you can refer to a simple, clean interface.
104 |
105 |
106 | ## Contract Reference
107 |
108 | This is a reference to most Laravel Contracts, as well as their Laravel "facade" counterparts:
109 |
110 | Contract | References Facade
111 | ------------- | -------------
112 | [Illuminate\Contracts\Auth\Guard](https://github.com/illuminate/contracts/blob/master/Auth/Guard.php) | Auth
113 | [Illuminate\Contracts\Auth\PasswordBroker](https://github.com/illuminate/contracts/blob/master/Auth/PasswordBroker.php) | Password
114 | [Illuminate\Contracts\Bus\Dispatcher](https://github.com/illuminate/contracts/blob/master/Bus/Dispatcher.php) | Bus
115 | [Illuminate\Contracts\Broadcasting\Broadcaster](https://github.com/illuminate/contracts/blob/master/Broadcasting/Broadcaster.php) |
116 | [Illuminate\Contracts\Cache\Repository](https://github.com/illuminate/contracts/blob/master/Cache/Repository.php) | Cache
117 | [Illuminate\Contracts\Cache\Factory](https://github.com/illuminate/contracts/blob/master/Cache/Factory.php) | Cache::driver()
118 | [Illuminate\Contracts\Config\Repository](https://github.com/illuminate/contracts/blob/master/Config/Repository.php) | Config
119 | [Illuminate\Contracts\Container\Container](https://github.com/illuminate/contracts/blob/master/Container/Container.php) | App
120 | [Illuminate\Contracts\Cookie\Factory](https://github.com/illuminate/contracts/blob/master/Cookie/Factory.php) | Cookie
121 | [Illuminate\Contracts\Cookie\QueueingFactory](https://github.com/illuminate/contracts/blob/master/Cookie/QueueingFactory.php) | Cookie::queue()
122 | [Illuminate\Contracts\Encryption\Encrypter](https://github.com/illuminate/contracts/blob/master/Encryption/Encrypter.php) | Crypt
123 | [Illuminate\Contracts\Events\Dispatcher](https://github.com/illuminate/contracts/blob/master/Events/Dispatcher.php) | Event
124 | [Illuminate\Contracts\Filesystem\Cloud](https://github.com/illuminate/contracts/blob/master/Filesystem/Cloud.php) |
125 | [Illuminate\Contracts\Filesystem\Factory](https://github.com/illuminate/contracts/blob/master/Filesystem/Factory.php) | File
126 | [Illuminate\Contracts\Filesystem\Filesystem](https://github.com/illuminate/contracts/blob/master/Filesystem/Filesystem.php) | File
127 | [Illuminate\Contracts\Foundation\Application](https://github.com/illuminate/contracts/blob/master/Foundation/Application.php) | App
128 | [Illuminate\Contracts\Hashing\Hasher](https://github.com/illuminate/contracts/blob/master/Hashing/Hasher.php) | Hash
129 | [Illuminate\Contracts\Logging\Log](https://github.com/illuminate/contracts/blob/master/Logging/Log.php) | Log
130 | [Illuminate\Contracts\Mail\MailQueue](https://github.com/illuminate/contracts/blob/master/Mail/MailQueue.php) | Mail::queue()
131 | [Illuminate\Contracts\Mail\Mailer](https://github.com/illuminate/contracts/blob/master/Mail/Mailer.php) | Mail
132 | [Illuminate\Contracts\Queue\Factory](https://github.com/illuminate/contracts/blob/master/Queue/Factory.php) | Queue::driver()
133 | [Illuminate\Contracts\Queue\Queue](https://github.com/illuminate/contracts/blob/master/Queue/Queue.php) | Queue
134 | [Illuminate\Contracts\Redis\Database](https://github.com/illuminate/contracts/blob/master/Redis/Database.php) | Redis
135 | [Illuminate\Contracts\Routing\Registrar](https://github.com/illuminate/contracts/blob/master/Routing/Registrar.php) | Route
136 | [Illuminate\Contracts\Routing\ResponseFactory](https://github.com/illuminate/contracts/blob/master/Routing/ResponseFactory.php) | Response
137 | [Illuminate\Contracts\Routing\UrlGenerator](https://github.com/illuminate/contracts/blob/master/Routing/UrlGenerator.php) | URL
138 | [Illuminate\Contracts\Support\Arrayable](https://github.com/illuminate/contracts/blob/master/Support/Arrayable.php) |
139 | [Illuminate\Contracts\Support\Jsonable](https://github.com/illuminate/contracts/blob/master/Support/Jsonable.php) |
140 | [Illuminate\Contracts\Support\Renderable](https://github.com/illuminate/contracts/blob/master/Support/Renderable.php) |
141 | [Illuminate\Contracts\Validation\Factory](https://github.com/illuminate/contracts/blob/master/Validation/Factory.php) | Validator::make()
142 | [Illuminate\Contracts\Validation\Validator](https://github.com/illuminate/contracts/blob/master/Validation/Validator.php) |
143 | [Illuminate\Contracts\View\Factory](https://github.com/illuminate/contracts/blob/master/View/Factory.php) | View::make()
144 | [Illuminate\Contracts\View\View](https://github.com/illuminate/contracts/blob/master/View/View.php) |
145 |
146 |
147 | ## How To Use Contracts
148 |
149 | So, how do you get an implementation of a contract? It's actually quite simple.
150 |
151 | Many types of classes in Laravel are resolved through the [service container](/{{version}}/container), including controllers, event listeners, middleware, queued jobs, and even route Closures. So, to get an implementation of a contract, you can just "type-hint" the interface in the constructor of the class being resolved.
152 |
153 | For example, take a look at this event listener:
154 |
155 | redis = $redis;
179 | }
180 |
181 | /**
182 | * Handle the event.
183 | *
184 | * @param NewUserRegistered $event
185 | * @return void
186 | */
187 | public function handle(NewUserRegistered $event)
188 | {
189 | //
190 | }
191 | }
192 |
193 | When the event listener is resolved, the service container will read the type-hints on the constructor of the class, and inject the appropriate value. To learn more about registering things in the service container, check out [its documentation](/{{version}}/container).
--------------------------------------------------------------------------------
/contributing.md:
--------------------------------------------------------------------------------
1 | # Guia para contribuir a la documentación
2 |
3 | Siempre envia la documentacion a su respectivo branch, actualmente el branch `master` se refiere a la version 5.1, y la `4.1` a la version 4.1, y asi con el resto.
4 | Antes de empezar con la traduccion de una pagina, asegurate antes de que no este siendo traducido por otra persona, verificando https://github.com/montogeek/laravel-docs-es/issues/21
5 |
--------------------------------------------------------------------------------
/contributions.md:
--------------------------------------------------------------------------------
1 | # Contribution Guide
2 |
3 | - [Bug Reports](#bug-reports)
4 | - [Core Development Discussion](#core-development-discussion)
5 | - [Which Branch?](#which-branch)
6 | - [Security Vulnerabilities](#security-vulnerabilities)
7 | - [Coding Style](#coding-style)
8 | - [Code Style Fixer](#code-style-fixer)
9 |
10 |
11 | ## Bug Reports
12 |
13 | To encourage active collaboration, Laravel strongly encourages pull requests, not just bug reports. "Bug reports" may also be sent in the form of a pull request containing a failing test.
14 |
15 | However, if you file a bug report, your issue should contain a title and a clear description of the issue. You should also include as much relevant information as possible and a code sample that demonstrates the issue. The goal of a bug report is to make it easy for yourself - and others - to replicate the bug and develop a fix.
16 |
17 | Remember, bug reports are created in the hope that others with the same problem will be able to collaborate with you on solving it. Do not expect that the bug report will automatically see any activity or that others will jump to fix it. Creating a bug report serves to help yourself and others start on the path of fixing the problem.
18 |
19 | The Laravel source code is managed on Github, and there are repositories for each of the Laravel projects:
20 |
21 | - [Laravel Framework](https://github.com/laravel/framework)
22 | - [Laravel Application](https://github.com/laravel/laravel)
23 | - [Laravel Documentation](https://github.com/laravel/docs)
24 | - [Laravel Cashier](https://github.com/laravel/cashier)
25 | - [Laravel Envoy](https://github.com/laravel/envoy)
26 | - [Laravel Homestead](https://github.com/laravel/homestead)
27 | - [Laravel Homestead Build Scripts](https://github.com/laravel/settler)
28 | - [Laravel Website](https://github.com/laravel/laravel.com)
29 | - [Laravel Art](https://github.com/laravel/art)
30 |
31 |
32 | ## Core Development Discussion
33 |
34 | Discussion regarding bugs, new features, and implementation of existing features takes place in the `#internals` channel of the [LaraChat](http://larachat.co) Slack team. Taylor Otwell, the maintainer of Laravel, is typically present in the channel on weekdays from 8am-5pm (UTC-06:00 or America/Chicago), and sporadically present in the channel at other times.
35 |
36 |
37 | ## Which Branch?
38 |
39 | **All** bug fixes should be sent to the latest stable branch. Bug fixes should **never** be sent to the `master` branch unless they fix features that exist only in the upcoming release.
40 |
41 | **Minor** features that are **fully backwards compatible** with the current Laravel release may be sent to the latest stable branch.
42 |
43 | **Major** new features should always be sent to the `master` branch, which contains the upcoming Laravel release.
44 |
45 | If you are unsure if your feature qualifies as a major or minor, please ask Taylor Otwell in the `#internals` channel of the [LaraChat](http://larachat.co) Slack team.
46 |
47 |
48 | ## Security Vulnerabilities
49 |
50 | If you discover a security vulnerability within Laravel, please send an e-mail to Taylor Otwell at taylor@laravel.com. All security vulnerabilities will be promptly addressed.
51 |
52 |
53 | ## Coding Style
54 |
55 | Laravel follows the [PSR-2](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md) coding standard and the [PSR-4](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-4-autoloader.md) autoloading standard.
56 |
57 | ### DocBlocks
58 |
59 | `@param` tags should **not be aligned** and arguments should be separated by **2 spaces**.
60 |
61 | Here's an example block:
62 |
63 | /**
64 | * Register a binding with the container.
65 | *
66 | * @param string|array $abstract
67 | * @param \Closure|string|null $concrete
68 | * @param bool $shared
69 | * @return void
70 | */
71 | public function bind($abstract, $concrete = null, $shared = false)
72 | {
73 | //
74 | }
75 |
76 |
77 | ### Code Style Fixer
78 |
79 | You may use the [PHP-CS-Fixer](https://github.com/FriendsOfPHP/PHP-CS-Fixer) to fix your code style before committing.
80 |
81 | To get started, [install the tool globally](https://github.com/FriendsOfPHP/PHP-CS-Fixer#globally-manual) and check the code style by issuing the following terminal command from your project's root directory:
82 |
83 | ```sh
84 | php-cs-fixer fix
85 | ```
--------------------------------------------------------------------------------
/database.md:
--------------------------------------------------------------------------------
1 | # Database: Getting Started
2 |
3 | - [Introduction](#introduction)
4 | - [Running Raw SQL Queries](#running-queries)
5 | - [Listening For Query Events](#listening-for-query-events)
6 | - [Database Transactions](#database-transactions)
7 | - [Using Multiple Database Connections](#accessing-connections)
8 |
9 |
10 | ## Introduction
11 |
12 | Laravel makes connecting with databases and running queries extremely simple across a variety of database back-ends using either raw SQL, the [fluent query builder](/{{version}}/queries), and the [Eloquent ORM](/{{version}}/eloquent). Currently, Laravel supports four database systems:
13 |
14 | - MySQL
15 | - Postgres
16 | - SQLite
17 | - SQL Server
18 |
19 |
20 | ### Configuration
21 |
22 | Laravel makes connecting with databases and running queries extremely simple. The database configuration for your application is located at `config/database.php`. In this file you may define all of your database connections, as well as specify which connection should be used by default. Examples for all of the supported database systems are provided in this file.
23 |
24 | By default, Laravel's sample [environment configuration](/{{version}}/installation#environment-configuration) is ready to use with [Laravel Homestead](/{{version}}/homestead), which is a convenient virtual machine for doing Laravel development on your local machine. Of course, you are free to modify this configuration as needed for your local database.
25 |
26 |
27 | #### Read / Write Connections
28 |
29 | Sometimes you may wish to use one database connection for SELECT statements, and another for INSERT, UPDATE, and DELETE statements. Laravel makes this a breeze, and the proper connections will always be used whether you are using raw queries, the query builder, or the Eloquent ORM.
30 |
31 | To see how read / write connections should be configured, let's look at this example:
32 |
33 | 'mysql' => [
34 | 'read' => [
35 | 'host' => '192.168.1.1',
36 | ],
37 | 'write' => [
38 | 'host' => '196.168.1.2'
39 | ],
40 | 'driver' => 'mysql',
41 | 'database' => 'database',
42 | 'username' => 'root',
43 | 'password' => '',
44 | 'charset' => 'utf8',
45 | 'collation' => 'utf8_unicode_ci',
46 | 'prefix' => '',
47 | ],
48 |
49 | Note that two keys have been added to the configuration array: `read` and `write`. Both of these keys have array values containing a single key: `host`. The rest of the database options for the `read` and `write` connections will be merged from the main `mysql` array.
50 |
51 | So, we only need to place items in the `read` and `write` arrays if we wish to override the values in the main array. So, in this case, `192.168.1.1` will be used as the "read" connection, while `192.168.1.2` will be used as the "write" connection. The database credentials, prefix, character set, and all other options in the main `mysql` array will be shared across both connections.
52 |
53 |
54 | ## Running Raw SQL Queries
55 |
56 | Once you have configured your database connection, you may run queries using the `DB` facade. The `DB` facade provides methods for each type of query: `select`, `update`, `insert`, `delete`, and `statement`.
57 |
58 | #### Running A Select Query
59 |
60 | To run a basic query, we can use the `select` method on the `DB` facade:
61 |
62 | $users]);
81 | }
82 | }
83 |
84 | The first argument passed to the `select` method is the raw SQL query, while the second argument is any parameter bindings that need to be bound to the query. Typically, these are the values of the `where` clause constraints. Parameter binding provides protection against SQL injection.
85 |
86 | The `select` method will always return an `array` of results. Each result within the array will be a PHP `StdClass` object, allowing you to access the values of the results:
87 |
88 | foreach ($users as $user) {
89 | echo $user->name;
90 | }
91 |
92 | #### Using Named Bindings
93 |
94 | Instead of using `?` to represent your parameter bindings, you may execute a query using named bindings:
95 |
96 | $results = DB::select('select * from users where id = :id', ['id' => 1]);
97 |
98 | #### Running An Insert Statement
99 |
100 | To execute an `insert` statement, you may use the `insert` method on the `DB` facade. Like `select`, this method takes the raw SQL query as its first argument, and bindings as the second argument:
101 |
102 | DB::insert('insert into users (id, name) values (?, ?)', [1, 'Dayle']);
103 |
104 | #### Running An Update Statement
105 |
106 | The `update` method should be used to update existing records in the database. The number of rows affected by the statement will be returned by the method:
107 |
108 | $affected = DB::update('update users set votes = 100 where name = ?', ['John']);
109 |
110 | #### Running A Delete Statement
111 |
112 | The `delete` method should be used to delete records from the database. Like `update`, the number of rows deleted will be returned:
113 |
114 | $deleted = DB::delete('delete from users');
115 |
116 | #### Running A General Statement
117 |
118 | Some database statements should not return any value. For these types of operations, you may use the `statement` method on the `DB` facade:
119 |
120 | DB::statement('drop table users');
121 |
122 |
123 | ### Listening For Query Events
124 |
125 | If you would like to receive each SQL query executed by your application, you may use the `listen` method. This method is useful for logging queries or debugging. You may register your query listener in a [service provider](/{{version}}/providers):
126 |
127 |
160 | ## Database Transactions
161 |
162 | To run a set of operations within a database transaction, you may use the `transaction` method on the `DB` facade. If an exception is thrown within the transaction `Closure`, the transaction will automatically be rolled back. If the `Closure` executes successfully, the transaction will automatically be committed. You don't need to worry about manually rolling back or committing while using the `transaction` method:
163 |
164 | DB::transaction(function () {
165 | DB::table('users')->update(['votes' => 1]);
166 |
167 | DB::table('posts')->delete();
168 | });
169 |
170 | #### Manually Using Transactions
171 |
172 | If you would like to begin a transaction manually and have complete control over rollbacks and commits, you may use the `beginTransaction` method on the `DB` facade:
173 |
174 | DB::beginTransaction();
175 |
176 | You can rollback the transaction via the `rollBack` method:
177 |
178 | DB::rollBack();
179 |
180 | Lastly, you can commit a transaction via the `commit` method:
181 |
182 | DB::commit();
183 |
184 | > **Note:** Using the `DB` facade's transaction methods also controls transactions for the [query builder](/{{version}}/queries) and [Eloquent ORM](/{{version}}/eloquent).
185 |
186 |
187 | ## Using Multiple Database Connections
188 |
189 | When using multiple connections, you may access each connection via the `connection` method on the `DB` facade. The `name` passed to the `connection` method should correspond to one of the connections listed in your `config/database.php` configuration file:
190 |
191 | $users = DB::connection('foo')->select(...);
192 |
193 | You may also access the raw, underlying PDO instance using the `getPdo` method on a connection instance:
194 |
195 | $pdo = DB::connection()->getPdo();
196 |
--------------------------------------------------------------------------------
/documentation.md:
--------------------------------------------------------------------------------
1 | - Inicio
2 | - [Notas de lanzamiento](/{{version}}/releases)
3 | - [Guia de actualización](/{{version}}/upgrade)
4 | - [Guia de contribución](/{{version}}/contributions)
5 | - [Documentación API](http://laravel.com/api/{{version}}/)
6 | - Configuración
7 | - [Instalación](/{{version}}/installation)
8 | - [Homestead](/{{version}}/homestead)
9 | - Tutoriales
10 | - [Principiante](/{{version}}/quickstart)
11 | - [Intermedio](/{{version}}/quickstart-intermediate)
12 | - Basico
13 | - **[Inicio rápido](/{{version}}/quickstart)**
14 | - [Middleware](/{{version}}/middleware)
15 | - [Controladores](/{{version}}/controllers)
16 | - [Peticiones](/{{version}}/requests)
17 | - [Respuestas](/{{version}}/responses)
18 | - [Vistas](/{{version}}/views)
19 | - [Plantillas Blade](/{{version}}/blade)
20 | - Fundaciones de arquitectura
21 | - [Ciclo de vida de una petición](/{{version}}/lifecycle)
22 | - [Estructura de la aplicación](/{{version}}/structure)
23 | - [Proveedores de servicio](/{{version}}/providers)
24 | - [Contenedor de servicio](/{{version}}/container)
25 | - [Contratos](/{{version}}/contracts)
26 | - [Facades](/{{version}}/facades)
27 | - Servicios
28 | - [Autenticación](/{{version}}/authentication)
29 | - [Autorización](/{{version}}/authorization)
30 | - [Consola Artisan](/{{version}}/artisan)
31 | - [Pagos](/{{version}}/billing)
32 | - [Cache](/{{version}}/cache)
33 | - [Coleciones](/{{version}}/collections)
34 | - [Elixir](/{{version}}/elixir)
35 | - [Encripción](/{{version}}/encryption)
36 | - [Errores & Logging](/{{version}}/errors)
37 | - [Eventos](/{{version}}/events)
38 | - [Sistema de archivos / Guardado en la nube](/{{version}}/filesystem)
39 | - [Hashing](/{{version}}/hashing)
40 | - [Helpers](/{{version}}/helpers)
41 | - [Localización](/{{version}}/localization)
42 | - [Correo](/{{version}}/mail)
43 | - [Desarrollo de paquetes](/{{version}}/packages)
44 | - [Paginación](/{{version}}/pagination)
45 | - [Colas](/{{version}}/queues)
46 | - [Redis](/{{version}}/redis)
47 | - [Sesión](/{{version}}/session)
48 | - [Tareas SSH](/{{version}}/envoy)
49 | - [Calendario de tareas](/{{version}}/scheduling)
50 | - [Testing](/{{version}}/testing)
51 | - [Validación](/{{version}}/validation)
52 | - Base de datos
53 | - [Inicio](/{{version}}/database)
54 | - [Contructor de consultas](/{{version}}/queries)
55 | - [Migraciones](/{{version}}/migrations)
56 | - [Semillas](/{{version}}/seeding)
57 | - Eloquent ORM
58 | - [Inicio](/{{version}}/eloquent)
59 | - [Relaciones](/{{version}}/eloquent-relationships)
60 | - [Colecciones](/{{version}}/eloquent-collections)
61 | - [Mutadores](/{{version}}/eloquent-mutators)
62 | - [Serialización](/{{version}}/eloquent-serialization)
63 |
--------------------------------------------------------------------------------
/eloquent-collections.md:
--------------------------------------------------------------------------------
1 | # Eloquent: Collections
2 |
3 | - [Introduction](#introduction)
4 | - [Available Methods](#available-methods)
5 | - [Custom Collections](#custom-collections)
6 |
7 |
8 | ## Introduction
9 |
10 | All multi-result sets returned by Eloquent are an instance of the `Illuminate\Database\Eloquent\Collection` object, including results retrieved via the `get` method or accessed via a relationship. The Eloquent collection object extends the Laravel [base collection](/{{version}}/collections), so it naturally inherits dozens of methods used to fluently work with the underlying array of Eloquent models.
11 |
12 | Of course, all collections also serve as iterators, allowing you to loop over them as if they were simple PHP arrays:
13 |
14 | $users = App\User::where('active', 1)->get();
15 |
16 | foreach ($users as $user) {
17 | echo $user->name;
18 | }
19 |
20 | However, collections are much more powerful than arrays and expose a variety of map / reduce operations using an intuitive interface. For example, let's remove all inactive models and gather the first name for each remaining user:
21 |
22 | $users = App\User::where('active', 1)->get();
23 |
24 | $names = $users->reject(function ($user) {
25 | return $user->active === false;
26 | })
27 | ->map(function ($user) {
28 | return $user->name;
29 | });
30 |
31 |
32 | ## Available Methods
33 |
34 | ### The Base Collection
35 |
36 | All Eloquent collections extend the base [Laravel collection](/{{version}}/collections) object; therefore, they inherit all of the powerful methods provided by the base collection class:
37 |
38 |
48 |
49 |
50 | [all](/{{version}}/collections#method-all)
51 | [chunk](/{{version}}/collections#method-chunk)
52 | [collapse](/{{version}}/collections#method-collapse)
53 | [contains](/{{version}}/collections#method-contains)
54 | [count](/{{version}}/collections#method-count)
55 | [diff](/{{version}}/collections#method-diff)
56 | [each](/{{version}}/collections#method-each)
57 | [filter](/{{version}}/collections#method-filter)
58 | [first](/{{version}}/collections#method-first)
59 | [flatten](/{{version}}/collections#method-flatten)
60 | [flip](/{{version}}/collections#method-flip)
61 | [forget](/{{version}}/collections#method-forget)
62 | [forPage](/{{version}}/collections#method-forpage)
63 | [get](/{{version}}/collections#method-get)
64 | [groupBy](/{{version}}/collections#method-groupby)
65 | [has](/{{version}}/collections#method-has)
66 | [implode](/{{version}}/collections#method-implode)
67 | [intersect](/{{version}}/collections#method-intersect)
68 | [isEmpty](/{{version}}/collections#method-isempty)
69 | [keyBy](/{{version}}/collections#method-keyby)
70 | [keys](/{{version}}/collections#method-keys)
71 | [last](/{{version}}/collections#method-last)
72 | [map](/{{version}}/collections#method-map)
73 | [merge](/{{version}}/collections#method-merge)
74 | [pluck](/{{version}}/collections#method-pluck)
75 | [pop](/{{version}}/collections#method-pop)
76 | [prepend](/{{version}}/collections#method-prepend)
77 | [pull](/{{version}}/collections#method-pull)
78 | [push](/{{version}}/collections#method-push)
79 | [put](/{{version}}/collections#method-put)
80 | [random](/{{version}}/collections#method-random)
81 | [reduce](/{{version}}/collections#method-reduce)
82 | [reject](/{{version}}/collections#method-reject)
83 | [reverse](/{{version}}/collections#method-reverse)
84 | [search](/{{version}}/collections#method-search)
85 | [shift](/{{version}}/collections#method-shift)
86 | [shuffle](/{{version}}/collections#method-shuffle)
87 | [slice](/{{version}}/collections#method-slice)
88 | [sort](/{{version}}/collections#method-sort)
89 | [sortBy](/{{version}}/collections#method-sortby)
90 | [sortByDesc](/{{version}}/collections#method-sortbydesc)
91 | [splice](/{{version}}/collections#method-splice)
92 | [sum](/{{version}}/collections#method-sum)
93 | [take](/{{version}}/collections#method-take)
94 | [toArray](/{{version}}/collections#method-toarray)
95 | [toJson](/{{version}}/collections#method-tojson)
96 | [transform](/{{version}}/collections#method-transform)
97 | [unique](/{{version}}/collections#method-unique)
98 | [values](/{{version}}/collections#method-values)
99 | [where](/{{version}}/collections#method-where)
100 | [whereLoose](/{{version}}/collections#method-whereloose)
101 | [zip](/{{version}}/collections#method-zip)
102 |
103 |
104 |
105 | ## Custom Collections
106 |
107 | If you need to use a custom `Collection` object with your own extension methods, you may override the `newCollection` method on your model:
108 |
109 |
9 | ## Introduction
10 |
11 | Accessors and mutators allow you to format Eloquent attributes when retrieving them from a model or setting their value. For example, you may want to use the [Laravel encrypter](/{{version}}/encryption) to encrypt a value while it is stored in the database, and then automatically decrypt the attribute when you access it on an Eloquent model.
12 |
13 | In addition to custom accessors and mutators, Eloquent can also automatically cast date fields to [Carbon](https://github.com/briannesbitt/Carbon) instances or even [cast text fields to JSON](#attribute-casting).
14 |
15 |
16 | ## Accessors & Mutators
17 |
18 | #### Defining An Accessor
19 |
20 | To define an accessor, create a `getFooAttribute` method on your model where `Foo` is the "camel" cased name of the column you wish to access. In this example, we'll define an accessor for the `first_name` attribute. The accessor will automatically be called by Eloquent when attempting to retrieve the value of `first_name`:
21 |
22 | first_name;
47 |
48 | #### Defining A Mutator
49 |
50 | To define a mutator, define a `setFooAttribute` method on your model where `Foo` is the "camel" cased name of the column you wish to access. So, again, let's define a mutator for the `first_name` attribute. This mutator will be automatically called when we attempt to set the value of the `first_name` attribute on the model:
51 |
52 | attributes['first_name'] = strtolower($value);
69 | }
70 | }
71 |
72 | The mutator will receive the value that is being set on the attribute, allowing you to manipulate the value and set the manipulated value on the Eloquent model's internal `$attributes` property. So, for example, if we attempt to set the `first_name` attribute to `Sally`:
73 |
74 | $user = App\User::find(1);
75 |
76 | $user->first_name = 'Sally';
77 |
78 | In this example, the `setFirstNameAttribute` function will be called with the value `Sally`. The mutator will then apply the `strtolower` function to the name and set its value in the internal `$attributes` array.
79 |
80 |
81 | ## Date Mutators
82 |
83 | By default, Eloquent will convert the `created_at` and `updated_at` columns to instances of [Carbon](https://github.com/briannesbitt/Carbon), which provides an assortment of helpful methods, and extends the native PHP `DateTime` class.
84 |
85 | You may customize which fields are automatically mutated, and even completely disable this mutation, by overriding the `$dates` property of your model:
86 |
87 | disabled_at = Carbon::now();
108 |
109 | $user->save();
110 |
111 | As noted above, when retrieving attributes that are listed in your `$dates` property, they will automatically be cast to [Carbon](https://github.com/briannesbitt/Carbon) instances, allowing you to use any of Carbon's methods on your attributes:
112 |
113 | $user = App\User::find(1);
114 |
115 | return $user->disabled_at->getTimestamp();
116 |
117 | By default, timestamps are formatted as `'Y-m-d H:i:s'`. If you need to customize the timestamp format, set the `$dateFormat` property on your model. This property determines how date attributes are stored in the database, as well as their format when the model is serialized to an array or JSON:
118 |
119 |
136 | ## Attribute Casting
137 |
138 | The `$casts` property on your model provides a convenient method of converting attributes to common data types. The `$casts` property should be an array where the key is the name of the attribute being cast, while the value is the type you wish to cast to the column to. The supported cast types are: `integer`, `real`, `float`, `double`, `string`, `boolean`, `object`, `array`, `collection`, `date` and `datetime`.
139 |
140 | For example, let's cast the `is_admin` attribute, which is stored in our database as an integer (`0` or `1`) to a boolean value:
141 |
142 | 'boolean',
157 | ];
158 | }
159 |
160 | Now the `is_admin` attribute will always be cast to a boolean when you access it, even if the underlying value is stored in the database as an integer:
161 |
162 | $user = App\User::find(1);
163 |
164 | if ($user->is_admin) {
165 | //
166 | }
167 |
168 | #### Array Casting
169 |
170 | The `array` cast type is particularly useful when working with columns that are stored as serialized JSON. For example, if your database has a `TEXT` field type that contains serialized JSON, adding the `array` cast to that attribute will automatically deserialize the attribute to a PHP array when you access it on your Eloquent model:
171 |
172 | 'array',
187 | ];
188 | }
189 |
190 | Once the cast is defined, you may access the `options` attribute and it will automatically be deserialized from JSON into a PHP array. When you set the value of the `options` attribute, the given array will automatically be serialized back into JSON for storage:
191 |
192 | $user = App\User::find(1);
193 |
194 | $options = $user->options;
195 |
196 | $options['key'] = 'value';
197 |
198 | $user->options = $options;
199 |
200 | $user->save();
--------------------------------------------------------------------------------
/eloquent-serialization.md:
--------------------------------------------------------------------------------
1 | # Eloquent: Serialization
2 |
3 | - [Introduction](#introduction)
4 | - [Basic Usage](#basic-usage)
5 | - [Hiding Attributes From JSON](#hiding-attributes-from-json)
6 | - [Appending Values To JSON](#appending-values-to-json)
7 |
8 |
9 | ## Introduction
10 |
11 | When building JSON APIs, you will often need to convert your models and relationships to arrays or JSON. Eloquent includes convenient methods for making these conversions, as well as controlling which attributes are included in your serializations.
12 |
13 |
14 | ## Basic Usage
15 |
16 | #### Converting A Model To An Array
17 |
18 | To convert a model and its loaded [relationships](/{{version}}/eloquent-relationships) to an array, you may use the `toArray` method. This method is recursive, so all attributes and all relations (including the relations of relations) will be converted to arrays:
19 |
20 | $user = App\User::with('roles')->first();
21 |
22 | return $user->toArray();
23 |
24 | You may also convert [collections](/{{version}}/eloquent-collections) to arrays:
25 |
26 | $users = App\User::all();
27 |
28 | return $users->toArray();
29 |
30 | #### Converting A Model To JSON
31 |
32 | To convert a model to JSON, you may use the `toJson` method. Like `toArray`, the `toJson` method is recursive, so all attributes and relations will be converted to JSON:
33 |
34 | $user = App\User::find(1);
35 |
36 | return $user->toJson();
37 |
38 | Alternatively, you may cast a model or collection to a string, which will automatically call the `toJson` method:
39 |
40 | $user = App\User::find(1);
41 |
42 | return (string) $user;
43 |
44 | Since models and collections are converted to JSON when cast to a string, you can return Eloquent objects directly from your application's routes or controllers:
45 |
46 | Route::get('users', function () {
47 | return App\User::all();
48 | });
49 |
50 |
51 | ## Hiding Attributes From JSON
52 |
53 | Sometimes you may wish to limit the attributes, such as passwords, that are included in your model's array or JSON representation. To do so, add a `$hidden` property definition to your model:
54 |
55 | **Note:** When hiding relationships, use the relationship's **method** name, not its dynamic property name.
72 |
73 | Alternatively, you may use the `visible` property to define a white-list of attributes that should be included in your model's array and JSON representation:
74 |
75 |
92 | ## Appending Values To JSON
93 |
94 | Occasionally, you may need to add array attributes that do not have a corresponding column in your database. To do so, first define an [accessor](/{{version}}/eloquent-mutators) for the value:
95 |
96 | attributes['admin'] == 'yes';
112 | }
113 | }
114 |
115 | Once you have created the accessor, add the attribute name to the `appends` property on the model:
116 |
117 |
7 | ## Configuration
8 |
9 | Before using Laravel's encrypter, you should set the `key` option of your `config/app.php` configuration file to a 32 character, random string. If this value is not properly set, all values encrypted by Laravel will be insecure.
10 |
11 |
12 | ## Basic Usage
13 |
14 | #### Encrypting A Value
15 |
16 | You may encrypt a value using the `Crypt` [facade](/{{version}}/facades). All encrypted values are encrypted using OpenSSL and the `AES-256-CBC` cipher. Furthermore, all encrypted values are signed with a message authentication code (MAC) to detect any modifications to the encrypted string.
17 |
18 | For example, we may use the `encrypt` method to encrypt a secret and store it on an [Eloquent model](/{{version}}/eloquent):
19 |
20 | fill([
43 | 'secret' => Crypt::encrypt($request->secret)
44 | ])->save();
45 | }
46 | }
47 |
48 | #### Decrypting A Value
49 |
50 | Of course, you may decrypt values using the `decrypt` method on the `Crypt` facade. If the value can not be properly decrypted, such as when the MAC is invalid, an `Illuminate\Contracts\Encryption\DecryptException` will be thrown:
51 |
52 | use Illuminate\Contracts\Encryption\DecryptException;
53 |
54 | try {
55 | $decrypted = Crypt::decrypt($encryptedValue);
56 | } catch (DecryptException $e) {
57 | //
58 | }
59 |
--------------------------------------------------------------------------------
/envoy.md:
--------------------------------------------------------------------------------
1 | # Envoy Task Runner
2 |
3 | - [Introduction](#introduction)
4 | - [Writing Tasks](#writing-tasks)
5 | - [Task Variables](#task-variables)
6 | - [Multiple Servers](#envoy-multiple-servers)
7 | - [Task Macros](#envoy-task-macros)
8 | - [Running Tasks](#envoy-running-tasks)
9 | - [Notifications](#envoy-notifications)
10 | - [HipChat](#hipchat)
11 | - [Slack](#slack)
12 |
13 |
14 | ## Introduction
15 |
16 | [Laravel Envoy](https://github.com/laravel/envoy) provides a clean, minimal syntax for defining common tasks you run on your remote servers. Using a Blade style syntax, you can easily setup tasks for deployment, Artisan commands, and more. Currently, Envoy only supports the Mac and Linux operating systems.
17 |
18 |
19 | ### Installation
20 |
21 | First, install Envoy using the Composer `global` command:
22 |
23 | composer global require "laravel/envoy=~1.0"
24 |
25 | Make sure to place the `~/.composer/vendor/bin` directory in your PATH so the `envoy` executable is found when you run the `envoy` command in your terminal.
26 |
27 | #### Updating Envoy
28 |
29 | You may also use Composer to keep your Envoy installation up to date:
30 |
31 | composer global update
32 |
33 |
34 | ## Writing Tasks
35 |
36 | All of your Envoy tasks should be defined in an `Envoy.blade.php` file in the root of your project. Here's an example to get you started:
37 |
38 | @servers(['web' => '192.168.1.1'])
39 |
40 | @task('foo', ['on' => 'web'])
41 | ls -la
42 | @endtask
43 |
44 | As you can see, an array of `@servers` is defined at the top of the file, allowing you to reference these servers in the `on` option of your task declarations. Within your `@task` declarations, you should place the Bash code that will be run on your server when the task is executed.
45 |
46 | #### Bootstrapping
47 |
48 | Sometimes, you may need to execute some PHP code before evaluating your Envoy tasks. You may use the ```@setup``` directive to declare variables and do general PHP work inside the Envoy file:
49 |
50 | @setup
51 | $now = new DateTime();
52 |
53 | $environment = isset($env) ? $env : "testing";
54 | @endsetup
55 |
56 | You may also use ```@include``` to include any outside PHP files:
57 |
58 | @include('vendor/autoload.php')
59 |
60 | #### Confirming Tasks
61 |
62 | If you would like to be prompted for confirmation before running a given task on your servers, you may add the `confirm` directive to your task declaration:
63 |
64 | @task('deploy', ['on' => 'web', 'confirm' => true])
65 | cd site
66 | git pull origin {{ $branch }}
67 | php artisan migrate
68 | @endtask
69 |
70 |
71 | ### Task Variables
72 |
73 | If needed, you may pass variables into the Envoy file using command line switches, allowing you to customize your tasks:
74 |
75 | envoy run deploy --branch=master
76 |
77 | You may use the options in your tasks via Blade's "echo" syntax:
78 |
79 | @servers(['web' => '192.168.1.1'])
80 |
81 | @task('deploy', ['on' => 'web'])
82 | cd site
83 | git pull origin {{ $branch }}
84 | php artisan migrate
85 | @endtask
86 |
87 |
88 | ### Multiple Servers
89 |
90 | You may easily run a task across multiple servers. First, add additional servers to your `@servers` declaration. Each server should be assigned a unique name. Once you have defined your additional servers, simply list the servers in the task declaration's `on` array:
91 |
92 | @servers(['web-1' => '192.168.1.1', 'web-2' => '192.168.1.2'])
93 |
94 | @task('deploy', ['on' => ['web-1', 'web-2']])
95 | cd site
96 | git pull origin {{ $branch }}
97 | php artisan migrate
98 | @endtask
99 |
100 | By default, the task will be executed on each server serially. Meaning, the task will finish running on the first server before proceeding to execute on the next server.
101 |
102 | #### Parallel Execution
103 |
104 | If you would like to run a task across multiple servers in parallel, add the `parallel` option to your task declaration:
105 |
106 | @servers(['web-1' => '192.168.1.1', 'web-2' => '192.168.1.2'])
107 |
108 | @task('deploy', ['on' => ['web-1', 'web-2'], 'parallel' => true])
109 | cd site
110 | git pull origin {{ $branch }}
111 | php artisan migrate
112 | @endtask
113 |
114 |
115 | ### Task Macros
116 |
117 | Macros allow you to define a set of tasks to be run in sequence using a single command. For instance, a `deploy` macro may run the `git` and `composer` tasks:
118 |
119 | @servers(['web' => '192.168.1.1'])
120 |
121 | @macro('deploy')
122 | git
123 | composer
124 | @endmacro
125 |
126 | @task('git')
127 | git pull origin master
128 | @endtask
129 |
130 | @task('composer')
131 | composer install
132 | @endtask
133 |
134 | Once the macro has been defined, you may run it via single, simple command:
135 |
136 | envoy run deploy
137 |
138 |
139 | ## Running Tasks
140 |
141 | To run a task from your `Envoy.blade.php` file, execute Envoy's `run` command, passing the command the name of the task or macro you would like to execute. Envoy will run the task and display the output from the servers as the task is running:
142 |
143 | envoy run task
144 |
145 |
146 |
147 | ## Notifications
148 |
149 |
150 | ### HipChat
151 |
152 | After running a task, you may send a notification to your team's HipChat room using Envoy's `@hipchat` directive. The directive accepts an API token, the name of the room, and the username to be displayed as the sender of the message:
153 |
154 | @servers(['web' => '192.168.1.1'])
155 |
156 | @task('foo', ['on' => 'web'])
157 | ls -la
158 | @endtask
159 |
160 | @after
161 | @hipchat('token', 'room', 'Envoy')
162 | @endafter
163 |
164 | If you wish, you may also pass a custom message to send to the HipChat room. Any variables available to your Envoy tasks will also be available when constructing the message:
165 |
166 | @after
167 | @hipchat('token', 'room', 'Envoy', "{$task} ran in the {$env} environment.")
168 | @endafter
169 |
170 |
171 | ### Slack
172 |
173 | In addition to HipChat, Envoy also supports sending notifications to [Slack](https://slack.com). The `@slack` directive accepts a Slack hook URL, a channel name, and the message you wish to send to the channel:
174 |
175 | @after
176 | @slack('hook', 'channel', 'message')
177 | @endafter
178 |
179 | You may retrieve your webhook URL by creating an `Incoming WebHooks` integration on Slack's website. The `hook` argument should be the entire webhook URL provided by the Incoming Webhooks Slack Integration. For example:
180 |
181 | https://hooks.slack.com/services/ZZZZZZZZZ/YYYYYYYYY/XXXXXXXXXXXXXXX
182 |
183 | You may provide one of the following as the channel argument:
184 |
185 | - To send the notification to a channel: `#channel`
186 | - To send the notification to a user: `@user`
187 |
188 |
--------------------------------------------------------------------------------
/errors.md:
--------------------------------------------------------------------------------
1 | # Errors & Logging
2 |
3 | - [Introduction](#introduction)
4 | - [Configuration](#configuration)
5 | - [The Exception Handler](#the-exception-handler)
6 | - [Report Method](#report-method)
7 | - [Render Method](#render-method)
8 | - [HTTP Exceptions](#http-exceptions)
9 | - [Custom HTTP Error Pages](#custom-http-error-pages)
10 | - [Logging](#logging)
11 |
12 |
13 | ## Introduction
14 |
15 | When you start a new Laravel project, error and exception handling is already configured for you. In addition, Laravel is integrated with the [Monolog](https://github.com/Seldaek/monolog) logging library, which provides support for a variety of powerful log handlers.
16 |
17 |
18 | ## Configuration
19 |
20 | #### Error Detail
21 |
22 | The amount of error detail your application displays through the browser is controlled by the `debug` configuration option in your `config/app.php` configuration file. By default, this configuration option is set to respect the `APP_DEBUG` environment variable, which is stored in your `.env` file.
23 |
24 | For local development, you should set the `APP_DEBUG` environment variable to `true`. In your production environment, this value should always be `false`.
25 |
26 | #### Log Modes
27 |
28 | Out of the box, Laravel supports `single`, `daily`, `syslog` and `errorlog` logging modes. For example, if you wish to use daily log files instead of a single file, you should simply set the `log` value in your `config/app.php` configuration file:
29 |
30 | 'log' => 'daily'
31 |
32 | #### Custom Monolog Configuration
33 |
34 | If you would like to have complete control over how Monolog is configured for your application, you may use the application's `configureMonologUsing` method. You should place a call to this method in your `bootstrap/app.php` file right before the `$app` variable is returned by the file:
35 |
36 | $app->configureMonologUsing(function($monolog) {
37 | $monolog->pushHandler(...);
38 | });
39 |
40 | return $app;
41 |
42 |
43 | ## The Exception Handler
44 |
45 | All exceptions are handled by the `App\Exceptions\Handler` class. This class contains two methods: `report` and `render`. We'll examine each of these methods in detail.
46 |
47 |
48 | ### The Report Method
49 |
50 | The `report` method is used to log exceptions or send them to an external service like [BugSnag](https://bugsnag.com). By default, the `report` method simply passes the exception to the base class where the exception is logged. However, you are free to log exceptions however you wish.
51 |
52 | For example, if you need to report different types of exceptions in different ways, you may use the PHP `instanceof` comparison operator:
53 |
54 | /**
55 | * Report or log an exception.
56 | *
57 | * This is a great spot to send exceptions to Sentry, Bugsnag, etc.
58 | *
59 | * @param \Exception $e
60 | * @return void
61 | */
62 | public function report(Exception $e)
63 | {
64 | if ($e instanceof CustomException) {
65 | //
66 | }
67 |
68 | return parent::report($e);
69 | }
70 |
71 | #### Ignoring Exceptions By Type
72 |
73 | The `$dontReport` property of the exception handler contains an array of exception types that will not be logged. By default, exceptions resulting from 404 errors are not written to your log files. You may add other exception types to this array as needed.
74 |
75 |
76 | ### The Render Method
77 |
78 | The `render` method is responsible for converting a given exception into an HTTP response that should be sent back to the browser. By default, the exception is passed to the base class which generates a response for you. However, you are free to check the exception type or return your own custom response:
79 |
80 | /**
81 | * Render an exception into an HTTP response.
82 | *
83 | * @param \Illuminate\Http\Request $request
84 | * @param \Exception $e
85 | * @return \Illuminate\Http\Response
86 | */
87 | public function render($request, Exception $e)
88 | {
89 | if ($e instanceof CustomException) {
90 | return response()->view('errors.custom', [], 500);
91 | }
92 |
93 | return parent::render($request, $e);
94 | }
95 |
96 |
97 | ## HTTP Exceptions
98 |
99 | Some exceptions describe HTTP error codes from the server. For example, this may be a "page not found" error (404), an "unauthorized error" (401) or even a developer generated 500 error. In order to generate such a response from anywhere in your application, use the following:
100 |
101 | abort(404);
102 |
103 | The `abort` method will immediately raise an exception which will be rendered by the exception handler. Optionally, you may provide the response text:
104 |
105 | abort(403, 'Unauthorized action.');
106 |
107 | This method may be used at any time during the request's lifecycle.
108 |
109 |
110 | ### Custom HTTP Error Pages
111 |
112 | Laravel makes it easy to return custom error pages for various HTTP status codes. For example, if you wish to customize the error page for 404 HTTP status codes, create a `resources/views/errors/404.blade.php`. This file will be served on all 404 errors generated by your application.
113 |
114 | The views within this directory should be named to match the HTTP status code they correspond to.
115 |
116 |
117 | ## Logging
118 |
119 | The Laravel logging facilities provide a simple layer on top of the powerful [Monolog](http://github.com/seldaek/monolog) library. By default, Laravel is configured to create daily log files for your application which are stored in the `storage/logs` directory. You may write information to the logs using the `Log` [facade](/{{version}}/facades):
120 |
121 | User::findOrFail($id)]);
142 | }
143 | }
144 |
145 | The logger provides the eight logging levels defined in [RFC 5424](http://tools.ietf.org/html/rfc5424): **emergency**, **alert**, **critical**, **error**, **warning**, **notice**, **info** and **debug**.
146 |
147 | Log::emergency($error);
148 | Log::alert($error);
149 | Log::critical($error);
150 | Log::error($error);
151 | Log::warning($error);
152 | Log::notice($error);
153 | Log::info($error);
154 | Log::debug($error);
155 |
156 | #### Contextual Information
157 |
158 | An array of contextual data may also be passed to the log methods. This contextual data will be formatted and displayed with the log message:
159 |
160 | Log::info('User failed to login.', ['id' => $user->id]);
161 |
162 | #### Accessing The Underlying Monolog Instance
163 |
164 | Monolog has a variety of additional handlers you may use for logging. If needed, you may access the underlying Monolog instance being used by Laravel:
165 |
166 | $monolog = Log::getMonolog();
--------------------------------------------------------------------------------
/facades.md:
--------------------------------------------------------------------------------
1 | # Facades
2 |
3 | - [Introduction](#introduction)
4 | - [Using Facades](#using-facades)
5 | - [Facade Class Reference](#facade-class-reference)
6 |
7 |
8 | ## Introduction
9 |
10 | Facades provide a "static" interface to classes that are available in the application's [service container](/{{version}}/container). Laravel ships with many facades, and you have probably been using them without even knowing it! Laravel "facades" serve as "static proxies" to underlying classes in the service container, providing the benefit of a terse, expressive syntax while maintaining more testability and flexibility than traditional static methods.
11 |
12 |
13 | ## Using Facades
14 |
15 | In the context of a Laravel application, a facade is a class that provides access to an object from the container. The machinery that makes this work is in the `Facade` class. Laravel's facades, and any custom facades you create, will extend the base `Illuminate\Support\Facades\Facade` class.
16 |
17 | A facade class only needs to implement a single method: `getFacadeAccessor`. It's the `getFacadeAccessor` method's job to define what to resolve from the container. The `Facade` base class makes use of the `__callStatic()` magic-method to defer calls from your facade to the resolved object.
18 |
19 | In the example below, a call is made to the Laravel cache system. By glancing at this code, one might assume that the static method `get` is being called on the `Cache` class:
20 |
21 | $user]);
41 | }
42 | }
43 |
44 | Notice that near the top of the file we are "importing" the `Cache` facade. This facade serves as a proxy to accessing the underlying implementation of the `Illuminate\Contracts\Cache\Factory` interface. Any calls we make using the facade will be passed to the underlying instance of Laravel's cache service.
45 |
46 | If we look at that `Illuminate\Support\Facades\Cache` class, you'll see that there is no static method `get`:
47 |
48 | class Cache extends Facade
49 | {
50 |
51 | /**
52 | * Get the registered name of the component.
53 | *
54 | * @return string
55 | */
56 | protected static function getFacadeAccessor() { return 'cache'; }
57 |
58 | }
59 |
60 | Instead, the `Cache` facade extends the base `Facade` class and defines the method `getFacadeAccessor()`. Remember, this method's job is to return the name of a service container binding. When a user references any static method on the `Cache` facade, Laravel resolves the `cache` binding from the [service container](/{{version}}/container) and runs the requested method (in this case, `get`) against that object.
61 |
62 |
63 | ## Facade Class Reference
64 |
65 | Below you will find every facade and its underlying class. This is a useful tool for quickly digging into the API documentation for a given facade root. The [service container binding](/{{version}}/container) key is also included where applicable.
66 |
67 | Facade | Class | Service Container Binding
68 | ------------- | ------------- | -------------
69 | App | [Illuminate\Foundation\Application](http://laravel.com/api/{{version}}/Illuminate/Foundation/Application.html) | `app`
70 | Artisan | [Illuminate\Console\Application](http://laravel.com/api/{{version}}/Illuminate/Console/Application.html) | `artisan`
71 | Auth | [Illuminate\Auth\AuthManager](http://laravel.com/api/{{version}}/Illuminate/Auth/AuthManager.html) | `auth`
72 | Auth (Instance) | [Illuminate\Auth\Guard](http://laravel.com/api/{{version}}/Illuminate/Auth/Guard.html) |
73 | Blade | [Illuminate\View\Compilers\BladeCompiler](http://laravel.com/api/{{version}}/Illuminate/View/Compilers/BladeCompiler.html) | `blade.compiler`
74 | Bus | [Illuminate\Contracts\Bus\Dispatcher](http://laravel.com/api/{{version}}/Illuminate/Contracts/Bus/Dispatcher.html) |
75 | Cache | [Illuminate\Cache\Repository](http://laravel.com/api/{{version}}/Illuminate/Cache/Repository.html) | `cache`
76 | Config | [Illuminate\Config\Repository](http://laravel.com/api/{{version}}/Illuminate/Config/Repository.html) | `config`
77 | Cookie | [Illuminate\Cookie\CookieJar](http://laravel.com/api/{{version}}/Illuminate/Cookie/CookieJar.html) | `cookie`
78 | Crypt | [Illuminate\Encryption\Encrypter](http://laravel.com/api/{{version}}/Illuminate/Encryption/Encrypter.html) | `encrypter`
79 | DB | [Illuminate\Database\DatabaseManager](http://laravel.com/api/{{version}}/Illuminate/Database/DatabaseManager.html) | `db`
80 | DB (Instance) | [Illuminate\Database\Connection](http://laravel.com/api/{{version}}/Illuminate/Database/Connection.html) |
81 | Event | [Illuminate\Events\Dispatcher](http://laravel.com/api/{{version}}/Illuminate/Events/Dispatcher.html) | `events`
82 | File | [Illuminate\Filesystem\Filesystem](http://laravel.com/api/{{version}}/Illuminate/Filesystem/Filesystem.html) | `files`
83 | Hash | [Illuminate\Contracts\Hashing\Hasher](http://laravel.com/api/{{version}}/Illuminate/Contracts/Hashing/Hasher.html) | `hash`
84 | Input | [Illuminate\Http\Request](http://laravel.com/api/{{version}}/Illuminate/Http/Request.html) | `request`
85 | Lang | [Illuminate\Translation\Translator](http://laravel.com/api/{{version}}/Illuminate/Translation/Translator.html) | `translator`
86 | Log | [Illuminate\Log\Writer](http://laravel.com/api/{{version}}/Illuminate/Log/Writer.html) | `log`
87 | Mail | [Illuminate\Mail\Mailer](http://laravel.com/api/{{version}}/Illuminate/Mail/Mailer.html) | `mailer`
88 | Password | [Illuminate\Auth\Passwords\PasswordBroker](http://laravel.com/api/{{version}}/Illuminate/Auth/Passwords/PasswordBroker.html) | `auth.password`
89 | Queue | [Illuminate\Queue\QueueManager](http://laravel.com/api/{{version}}/Illuminate/Queue/QueueManager.html) | `queue`
90 | Queue (Instance) | [Illuminate\Queue\QueueInterface](http://laravel.com/api/{{version}}/Illuminate/Queue/QueueInterface.html) |
91 | Queue (Base Class) | [Illuminate\Queue\Queue](http://laravel.com/api/{{version}}/Illuminate/Queue/Queue.html) |
92 | Redirect | [Illuminate\Routing\Redirector](http://laravel.com/api/{{version}}/Illuminate/Routing/Redirector.html) | `redirect`
93 | Redis | [Illuminate\Redis\Database](http://laravel.com/api/{{version}}/Illuminate/Redis/Database.html) | `redis`
94 | Request | [Illuminate\Http\Request](http://laravel.com/api/{{version}}/Illuminate/Http/Request.html) | `request`
95 | Response | [Illuminate\Contracts\Routing\ResponseFactory](http://laravel.com/api/{{version}}/Illuminate/Contracts/Routing/ResponseFactory.html) |
96 | Route | [Illuminate\Routing\Router](http://laravel.com/api/{{version}}/Illuminate/Routing/Router.html) | `router`
97 | Schema | [Illuminate\Database\Schema\Blueprint](http://laravel.com/api/{{version}}/Illuminate/Database/Schema/Blueprint.html) |
98 | Session | [Illuminate\Session\SessionManager](http://laravel.com/api/{{version}}/Illuminate/Session/SessionManager.html) | `session`
99 | Session (Instance) | [Illuminate\Session\Store](http://laravel.com/api/{{version}}/Illuminate/Session/Store.html) |
100 | Storage | [Illuminate\Contracts\Filesystem\Factory](http://laravel.com/api/{{version}}/Illuminate/Contracts/Filesystem/Factory.html) | `filesystem`
101 | URL | [Illuminate\Routing\UrlGenerator](http://laravel.com/api/{{version}}/Illuminate/Routing/UrlGenerator.html) | `url`
102 | Validator | [Illuminate\Validation\Factory](http://laravel.com/api/{{version}}/Illuminate/Validation/Factory.html) | `validator`
103 | Validator (Instance) | [Illuminate\Validation\Validator](http://laravel.com/api/{{version}}/Illuminate/Validation/Validator.html) |
104 | View | [Illuminate\View\Factory](http://laravel.com/api/{{version}}/Illuminate/View/Factory.html) | `view`
105 | View (Instance) | [Illuminate\View\View](http://laravel.com/api/{{version}}/Illuminate/View/View.html) |
106 |
--------------------------------------------------------------------------------
/filesystem.md:
--------------------------------------------------------------------------------
1 | # Filesystem / Cloud Storage
2 |
3 | - [Introduction](#introduction)
4 | - [Configuration](#configuration)
5 | - [Basic Usage](#basic-usage)
6 | - [Obtaining Disk Instances](#obtaining-disk-instances)
7 | - [Retrieving Files](#retrieving-files)
8 | - [Storing Files](#storing-files)
9 | - [Deleting Files](#deleting-files)
10 | - [Directories](#directories)
11 | - [Custom Filesystems](#custom-filesystems)
12 |
13 |
14 | ## Introduction
15 |
16 | Laravel provides a powerful filesystem abstraction thanks to the wonderful [Flysystem](https://github.com/thephpleague/flysystem) PHP package by Frank de Jonge. The Laravel Flysystem integration provides simple to use drivers for working with local filesystems, Amazon S3, and Rackspace Cloud Storage. Even better, it's amazingly simple to switch between these storage options as the API remains the same for each system.
17 |
18 |
19 | ## Configuration
20 |
21 | The filesystem configuration file is located at `config/filesystems.php`. Within this file you may configure all of your "disks". Each disk represents a particular storage driver and storage location. Example configurations for each supported driver is included in the configuration file. So, simply modify the configuration to reflect your storage preferences and credentials.
22 |
23 | Of course, you may configure as many disks as you like, and may even have multiple disks that use the same driver.
24 |
25 | #### The Local Driver
26 |
27 | When using the `local` driver, note that all file operations are relative to the `root` directory defined in your configuration file. By default, this value is set to the `storage/app` directory. Therefore, the following method would store a file in `storage/app/file.txt`:
28 |
29 | Storage::disk('local')->put('file.txt', 'Contents');
30 |
31 | #### Other Driver Prerequisites
32 |
33 | Before using the S3 or Rackspace drivers, you will need to install the appropriate package via Composer:
34 |
35 | - Amazon S3: `league/flysystem-aws-s3-v3 ~1.0`
36 | - Rackspace: `league/flysystem-rackspace ~1.0`
37 |
38 |
39 | ## Basic Usage
40 |
41 |
42 | ### Obtaining Disk Instances
43 |
44 | The `Storage` facade may be used to interact with any of your configured disks. For example, you may use the `put` method on the facade to store an avatar on the default disk. If you call methods on the `Storage` facade without first calling the `disk` method, the method call will automatically be passed to the default disk:
45 |
46 | id,
69 | file_get_contents($request->file('avatar')->getRealPath())
70 | );
71 | }
72 | }
73 |
74 | When using multiple disks, you may access a particular disk using the `disk` method on the `Storage` facade. Of course, you may continue to chain methods to execute methods on the disk:
75 |
76 | $disk = Storage::disk('s3');
77 |
78 | $contents = Storage::disk('local')->get('file.jpg')
79 |
80 |
81 | ### Retrieving Files
82 |
83 | The `get` method may be used to retrieve the contents of a given file. The raw string contents of the file will be returned by the method:
84 |
85 | $contents = Storage::get('file.jpg');
86 |
87 | The `has` method may be used to determine if a given file exists on the disk:
88 |
89 | $exists = Storage::disk('s3')->has('file.jpg');
90 |
91 | #### File Meta Information
92 |
93 | The `size` method may be used to get the size of the file in bytes:
94 |
95 | $size = Storage::size('file1.jpg');
96 |
97 | The `lastModified` method returns the UNIX timestamp of the last time the file was modified:
98 |
99 | $time = Storage::lastModified('file1.jpg');
100 |
101 |
102 | ### Storing Files
103 |
104 | The `put` method may be used to store a file on disk. You may also pass a PHP `resource` to the `put` method, which will use Flysystem's underlying stream support. Using streams is greatly recommended when dealing with large files:
105 |
106 | Storage::put('file.jpg', $contents);
107 |
108 | Storage::put('file.jpg', $resource);
109 |
110 | The `copy` method may be used to copy an existing file to a new location on the disk:
111 |
112 | Storage::copy('old/file1.jpg', 'new/file1.jpg');
113 |
114 | The `move` method may be used to rename or move an existing file to a new location:
115 |
116 | Storage::move('old/file1.jpg', 'new/file1.jpg');
117 |
118 | #### Prepending / Appending To Files
119 |
120 | The `prepend` and `append` methods allow you to easily insert content at the beginning or end of a file:
121 |
122 | Storage::prepend('file.log', 'Prepended Text');
123 |
124 | Storage::append('file.log', 'Appended Text');
125 |
126 |
127 | ### Deleting Files
128 |
129 | The `delete` method accepts a single filename or an array of files to remove from the disk:
130 |
131 | Storage::delete('file.jpg');
132 |
133 | Storage::delete(['file1.jpg', 'file2.jpg']);
134 |
135 |
136 | ### Directories
137 |
138 | #### Get All Files Within A Directory
139 |
140 | The `files` method returns an array of all of the files in a given directory. If you would like to retrieve a list of all files within a given directory including all sub-directories, you may use the `allFiles` method:
141 |
142 | $files = Storage::files($directory);
143 |
144 | $files = Storage::allFiles($directory);
145 |
146 | #### Get All Directories Within A Directory
147 |
148 | The `directories` method returns an array of all the directories within a given directory. Additionally, you may use the `allDirectories` method to get a list of all directories within a given directory and all of its sub-directories:
149 |
150 | $directories = Storage::directories($directory);
151 |
152 | // Recursive...
153 | $directories = Storage::allDirectories($directory);
154 |
155 | #### Create A Directory
156 |
157 | The `makeDirectory` method will create the given directory, including any needed sub-directories:
158 |
159 | Storage::makeDirectory($directory);
160 |
161 | #### Delete A Directory
162 |
163 | Finally, the `deleteDirectory` may be used to remove a directory, including all of its files, from the disk:
164 |
165 | Storage::deleteDirectory($directory);
166 |
167 |
168 | ## Custom Filesystems
169 |
170 | Laravel's Flysystem integration provides drivers for several "drivers" out of the box; however, Flysystem is not limited to these and has adapters for many other storage systems. You can create a custom driver if you want to use one of these additional adapters in your Laravel application.
171 |
172 | In order to set up the custom filesystem you will need to create a [service provider](/{{version}}/providers) such as `DropboxServiceProvider`. In the provider's `boot` method, you may use the `Storage` facade's `extend` method to define the custom driver:
173 |
174 |
7 | ## Introduction
8 |
9 | The Laravel `Hash` [facade](/{{version}}/facades) provides secure Bcrypt hashing for storing user passwords. If you are using the `AuthController` controller that is included with your Laravel application, it will automatically use Bcrypt for registration and authentication.
10 |
11 | Bcrypt is a great choice for hashing passwords because its "work factor" is adjustable, which means that the time it takes to generate a hash can be increased as hardware power increases.
12 |
13 |
14 | ## Basic Usage
15 |
16 | You may hash a password by calling the `make` method on the `Hash` facade:
17 |
18 | fill([
43 | 'password' => Hash::make($request->newPassword)
44 | ])->save();
45 | }
46 | }
47 |
48 | Alternatively, you may also use the global `bcrypt` helper function:
49 |
50 | bcrypt('plain-text');
51 |
52 | #### Verifying A Password Against A Hash
53 |
54 | The `check` method allows you to verify that a given plain-text string corresponds to a given hash. However, if you are using the `AuthController` [included with Laravel](/{{version}}/authentication), you will probably not need to use this directly, as the included authentication controller automatically calls this method:
55 |
56 | if (Hash::check('plain-text', $hashedPassword)) {
57 | // The passwords match...
58 | }
59 |
60 | #### Checking If A Password Needs To Be Rehashed
61 |
62 | The `needsRehash` function allows you to determine if the work factor used by the hasher has changed since the password was hashed:
63 |
64 | if (Hash::needsRehash($hashed)) {
65 | $hashed = Hash::make('plain-text');
66 | }
67 |
--------------------------------------------------------------------------------
/installation.md:
--------------------------------------------------------------------------------
1 | # Instalación
2 |
3 | - [Instalación](#installation)
4 | - [Configuración](#configuration)
5 | - [Configuración básica](#basic-configuration)
6 | - [Configuración de entorno](#environment-configuration)
7 | - [Configuración de caché](#configuration-caching)
8 | - [Accesando a variables de configuraciones](#accessing-configuration-values)
9 | - [Nombrando a su aplicación](#naming-your-application)
10 | - [Modo de mantenimiento](#maintenance-mode)
11 |
12 |
13 | ## Instalación
14 |
15 | ### Requerimientos del servidor
16 |
17 | El framework Laravel exige algunos requerimientos. Desde luego, todos esos requerimientos vienen preconfigurados en la máquina virtual [Laravel Homestead](/{{version}}/homestead):
18 |
19 |
20 | - PHP >= 5.5.9
21 | - OpenSSL PHP Extension
22 | - PDO PHP Extension
23 | - Mbstring PHP Extension
24 | - Tokenizer PHP Extension
25 |
26 |
27 |
28 | ### Instalar Laravel
29 |
30 | Laravel utiliza [Composer](http://getcomposer.org) para administrar sus dependencias. Dicho eso, antes de poder usar Laravel, asegúrese que su máquina tenga Composer instalado.
31 |
32 | #### Vía el Instalador Laravel
33 |
34 | Primero, descargue el Instalador de Laravel utilizando Composer:
35 |
36 | composer global require "laravel/installer=~1.1"
37 |
38 | Asegúrese de agregar el directorio `~/.composer/vendor/bin` a tu variable PATH así, el ejecutable `laravel` puede ser localizado por su sistema.
39 |
40 | Una vez instalado, el simple comando `laravel new` creará una nueva instalación de Laravel en el directorio que usted eligió. Por ejemplo, `laravel new blog` crea un directorio llamado `blog` con los archivos para una nueva instalación de Laravel con todas las dependencias ya instaladas. Ese método es mas eficiente que la instalación usando a Composer:
41 |
42 | laravel new blog
43 |
44 | #### Vía Composer Create-Project
45 |
46 | También puede instalar Laravel con el comando de Composer `create-project` desde su terminal:
47 |
48 | composer create-project laravel/laravel --prefer-dist
49 |
50 |
51 | ## Configuración
52 |
53 |
54 | ### Configuración Básica
55 |
56 | Todos los archivos de configuración de Laravel se encuentan en la carpeta `config`. Cada posible opción cuenta con documentación. Asegúrese de eharle un vistazo a esos archivos y familiarizarse con las opciones disponibles.
57 |
58 | #### Permisos en los directorio
59 |
60 | Después de instalar a Laravel, es posible que necesitará configurar algunos permisos. Los directorios dentro `storage` y los de `bootstrap/cache` deben modificables por el servidor. Si usted está usando la máquina virtual [Homestead](/{{version}}/homestead), esos permisos ya están configurados.
61 |
62 | #### Código de la Aplicación
63 |
64 | Lo siguiente que tiene que hacer después de la instalación es configurar el código aleatorio de su aplicación. Si instaló Laravel vía Composer o el Instalador de Laravel, el código viene configirado por el comando `key:generate`. Generalmente, el código es una cadena de 32 carácteres. El código puede ser seteado en el archivo de configuración de entorno `.env`. Si todavía usted no ha renombrado el archivo `.env.example` a `.env`, debe hacerlo ahora. **Si la aplicación no cuenta con un código, las sessiones y otras informaciones encriptadas no serán seguras!**
65 |
66 | #### Configuraciones adicionales
67 |
68 | Generalmente, Laravel no requiere otras configuraciones. A ese punto usted puede empezar a progamar! Sin embargo, quizá querrá revisar el archivo `config/app.php` y su documentación. Contiene varias opciones como por ejemplo `timezone` y `locale` que usted deberá configurar dependiendo de su aplicación.
69 |
70 | Quiźa querrá configurar algunos componente de Laravel, como:
71 |
72 | - [Cache](/{{version}}/cache#configuration)
73 | - [Database](/{{version}}/database#configuration)
74 | - [Session](/{{version}}/session#configuration)
75 |
76 | Una vez instalado, debe tambíen [configurar su variables de entorno](/{{version}}/installation#environment-configuration).
77 |
78 |
79 | #### URL amigables
80 |
81 | **Apache**
82 |
83 | El framework con el archivo `public/.htaccess` que permite ver los URL sin el `index.php`. Si está usando Apache como de Laravel, asegúrese de activar el módulo `mod_rewrite`.
84 |
85 | En caso de que el archivo `.htaccess` que viene con Laravel no funciona para usted, puede probar con el siguiente:
86 |
87 | Options +FollowSymLinks
88 | RewriteEngine On
89 |
90 | RewriteCond %{REQUEST_FILENAME} !-d
91 | RewriteCond %{REQUEST_FILENAME} !-f
92 | RewriteRule ^ index.php [L]
93 |
94 | **Nginx**
95 |
96 | En Nginx, usted puede utilizar la siguiente directiva para tener URL "amigables":
97 |
98 | location / {
99 | try_files $uri $uri/ /index.php?$query_string;
100 | }
101 |
102 | Por supuesto, usando [Homestead](/{{version}}/homestead), las URL amiables serán configuradas automaticamente.
103 |
104 |
105 | ### Configuración de entorno
106 |
107 | Generalmente, es útil tener diferentes configuraciones basado en el entorno que su aplicación está corriendo. Por ejemplo, puede tener localmente un controlador de caché diferente al que se está usando en su entorno de produción. Es bastante facil utilizando la configuración basada en el entorno.
108 |
109 | Para hacer eso facil como un juego de niño, Laravel utiliza la librería PHP [DotEnv](https://github.com/vlucas/phpdotenv) mantenida por Vance Lucas. En una instalación nueva de Laravel, hay un arcivo en la raíz de su aplicación llamado `.env.example`. Si usted usó Composer para instalar Laravel, ese archivo se renombró a `.env`. Otra manera, tendrá que hacer eso manualmente.
110 |
111 | Todas la variables en el archivo `.env` serán cargadas a la variable super-global de PHP `$_ENV` cada vez que su aplicación recibe una consulta http. Puede usar el método corto `env` para recuperar valores de esas variables. De hecho, si usted abre algunos de los archivos de configuración de Larevel, puede ver muchas opciones utilizando ese método corto!
112 |
113 | Siéntese seguro de modificar esas variables según las necesidaddes de su aplicación en local o producción. Ten en cuenta que, el `.env` no debe ser subido al control de versión de su aplicación, ya que cada desarrollador / servidor tiene necesidades diferentes en cuanto a configuración del entorno.
114 |
115 | Si está desarrollando en equipo, usted querrá incluir un archivo `.env.example`. Al agregar variables libres (place-holder) en el archivo de ejemplo, los otros desarrolladores de su equipo pueden claramente ver cúales son las variables que la aplicación requiera.
116 |
117 | #### Accesando al entorno actual de la aplicación
118 |
119 | El entorno actual de la aplicacion esta determinado por la variable `APP_ENV` de tu archivo `.env`. Puedes acceder a su valor utilizando el método `environment` que se encuenta en el [facade](/{{version}}/facades)) `App`:
120 |
121 | $environment = App::environment();
122 |
123 | También puede pasar argumentos al método `environment` para verificar que el entorno iguale a un valor dado. Si es necesario, puede pasar múltiples valores:
124 |
125 | if (App::environment('local')) {
126 | // el entorno es local
127 | }
128 |
129 | if (App::environment('local', 'staging')) {
130 | // El entorno es local o staging...
131 | }
132 |
133 | También puede utilizar el métdo rápido `app` en lugar del facade:
134 |
135 | $environment = app()->environment();
136 |
137 |
138 | ### Configuración de caché
139 |
140 | Para dar a la aplicación una mejora de rendimiento, debe meter en caché todos sus archivos de configuración usando el comando Artisan `config:cache`. Eso resultará en la combinación de todas las opciones en un sólo archivo que Laravel pueda carga más rápido.
141 |
142 | Usted debe adquirir el costumbre de ejecutar el comando `config:cache` como parte de su rutina de despliegue de su aplicación. El comando no debería ser ejecutado durante el desarrollo de tu aplicación ya que configuración tiende a cambiar bastante durante esta etapa.
143 |
144 |
145 | ### Accesando a variables de configuraciones
146 |
147 | Puede facilmente accesar a las variables de configuración de su aplicación usando el método rápido `config`. El valor puede ser accesido con el sintaxis de "punto", que incluye el nombre del archivo y la opción que se desea accesar. Si la opción no existe, se puede setear un valor por defector para ser retornado en lugar de null:
148 |
149 | $value = config('app.timezone');
150 |
151 | Para setear el valor de una opción de configuración en tiempo de ejecución, pasamos un arreglo al método rápido `config`:
152 |
153 | config(['app.timezone' => 'America/Chicago']);
154 |
155 |
156 | ### Nombrando a su aplicación
157 |
158 | Después de instalar Laravel, es posible que querrá "nombrar" a su aplicación. Por defecto, el directorio `app` directory está bajo el espacio de nombre `App`,y es autocargado por Composer usando [El estándar de autocarga PSR-4](http://www.php-fig.org/psr/psr-4/). Pero, si desea que el espacio de nombre sea el nombre de su aplicación por ejemplo, puede facilmente ejecutar el comando Artisan `app:name`.
159 |
160 | Por ejemplo, si su aplicación se llama "Horsefly", usted deberá ejecutar el siguiente comando en la raíz de la aplicación:
161 |
162 | php artisan app:name Horsefly
163 |
164 | Renombrar a su aplicación es totalment opcional, y puede perfectamente guardar el espacio de nombre por defecto `App`.
165 |
166 |
167 | ## Modo de mantenimiento
168 |
169 | Cuando la aplicación se encuentra en modo de mantenimiento, una vista por defecto será retornando para todas la consultas http. Es la manera mas facil de "desabilitar" la aplicación mientras está actualizando o dando mantenimiento. El chequeo de modo de mantenimiento viene incluido en capa de middleware de la aplicación. En modo de mantenimiento, la aplicación dispara la excepción `HttpException` con el código de estado 503.
170 |
171 | Para pasar a modo de mantenimiento, solamente ejecute el comando Artisan `down`:
172 |
173 | php artisan down
174 |
175 | Para salir del modo de mantemiento, ejecute el comando `up`:
176 |
177 | php artisan up
178 |
179 | ### Plantilla de Respuesta para modo de Mantenimiento
180 |
181 | La plantilla por defecto en modo de manteniento, se encuentra en `resources/views/errors/503.blade.php`.
182 |
183 | ### Modo de mantenimiento & Colas
184 |
185 | En modo de Mantenimiento, [los ejecutadores de colas](/{{version}}/queues) serán manejado. Lo jobs se reanudarán una vez que la aplicación está fuera de mantenimiento.
186 |
--------------------------------------------------------------------------------
/license.md:
--------------------------------------------------------------------------------
1 | The MIT License (MIT)
2 | Copyright © Taylor Otwell
3 |
4 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
5 |
6 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
7 |
8 | THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
--------------------------------------------------------------------------------
/lifecycle.md:
--------------------------------------------------------------------------------
1 | # Request Lifecycle
2 |
3 | - [Introduction](#introduction)
4 | - [Lifecycle Overview](#lifecycle-overview)
5 | - [Focus On Service Providers](#focus-on-service-providers)
6 |
7 |
8 | ## Introduction
9 |
10 | When using any tool in the "real world", you feel more confident if you understand how that tool works. Application development is no different. When you understand how your development tools function, you feel more comfortable and confident using them.
11 |
12 | The goal of this document is to give you a good, high-level overview of how the Laravel framework "works". By getting to know the overall framework better, everything feels less "magical" and you will be more confident building your applications.
13 |
14 | If you don't understand all of the terms right away, don't lose heart! Just try to get a basic grasp of what is going on, and your knowledge will grow as you explore other sections of the documentation.
15 |
16 |
17 | ## Lifecycle Overview
18 |
19 | ### First Things
20 |
21 | The entry point for all requests to a Laravel application is the `public/index.php` file. All requests are directed to this file by your web server (Apache / Nginx) configuration. The `index.php` file doesn't contain much code. Rather, it is simply a starting point for loading the rest of the framework.
22 |
23 | The `index.php` file loads the Composer generated autoloader definition, and then retrieves an instance of the Laravel application from `bootstrap/app.php` script. The first action taken by Laravel itself is to create an instance of the application / [service container](/{{version}}/container).
24 |
25 | ### HTTP / Console Kernels
26 |
27 | Next, the incoming request is sent to either the HTTP kernel or the console kernel, depending on the type of request that is entering the application. These two kernels serve as the central location that all requests flow through. For now, let's just focus on the HTTP kernel, which is located in `app/Http/Kernel.php`.
28 |
29 | The HTTP kernel extends the `Illuminate\Foundation\Http\Kernel` class, which defines an array of `bootstrappers` that will be run before the request is executed. These bootstrappers configure error handling, configure logging, [detect the application environment](/{{version}}/installation#environment-configuration), and perform other tasks that need to be done before the request is actually handled.
30 |
31 | The HTTP kernel also defines a list of HTTP [middleware](/{{version}}/middleware) that all requests must pass through before being handled by the application. These middleware handle reading and writing the [HTTP session](/{{version}}/session), determine if the application is in maintenance mode, [verifying the CSRF token](/{{version}}/routing#csrf-protection), and more.
32 |
33 | The method signature for the HTTP kernel's `handle` method is quite simple: receive a `Request` and return a `Response`. Think of the Kernel as being a big black box that represents your entire application. Feed it HTTP requests and it will return HTTP responses.
34 |
35 | #### Service Providers
36 |
37 | One of the most important Kernel bootstrapping actions is loading the [service providers](/{{version}}/providers) for your application. All of the service providers for the application are configured in the `config/app.php` configuration file's `providers` array. First, the `register` method will be called on all providers, then, once all providers have been registered, the `boot` method will be called.
38 |
39 | Service providers are responsible for bootstrapping all of the framework's various components, such as the database, queue, validation, and routing components. Since they bootstrap and configure every feature offered by the framework, service providers are the most important aspect of the entire Laravel bootstrap process.
40 |
41 | #### Dispatch Request
42 |
43 | Once the application has been bootstrapped and all service providers have been registered, the `Request` will be handed off to the router for dispatching. The router will dispatch the request to a route or controller, as well as run any route specific middleware.
44 |
45 |
46 | ## Focus On Service Providers
47 |
48 | Service providers are truly the key to bootstrapping a Laravel application. The application instance is created, the service providers are registered, and the request is handed to the bootstrapped application. It's really that simple!
49 |
50 | Having a firm grasp of how a Laravel application is built and bootstrapped via service providers is very valuable. Of course, your application's default service providers are stored in the `app/Providers` directory.
51 |
52 | By default, the `AppServiceProvider` is fairly empty. This provider is a great place to add your application's own bootstrapping and service container bindings. Of course, for large applications, you may wish to create several service providers, each with a more granular type of bootstrapping.
53 |
--------------------------------------------------------------------------------
/localization.md:
--------------------------------------------------------------------------------
1 | # Localization
2 |
3 | - [Introduction](#introduction)
4 | - [Basic Usage](#basic-usage)
5 | - [Pluralization](#pluralization)
6 | - [Overriding Vendor Language Files](#overriding-vendor-language-files)
7 |
8 |
9 | ## Introduction
10 |
11 | Laravel's localization features provide a convenient way to retrieve strings in various languages, allowing you to easily support multiple languages within your application.
12 |
13 | Language strings are stored in files within the `resources/lang` directory. Within this directory there should be a subdirectory for each language supported by the application:
14 |
15 | /resources
16 | /lang
17 | /en
18 | messages.php
19 | /es
20 | messages.php
21 |
22 | All language files simply return an array of keyed strings. For example:
23 |
24 | 'Welcome to our application'
28 | ];
29 |
30 | #### Configuring The Locale
31 |
32 | The default language for your application is stored in the `config/app.php` configuration file. Of course, you may modify this value to suit the needs of your application. You may also change the active language at runtime using the `setLocale` method on the `App` facade:
33 |
34 | Route::get('welcome/{locale}', function ($locale) {
35 | App::setLocale($locale);
36 |
37 | //
38 | });
39 |
40 | You may also configure a "fallback language", which will be used when the active language does not contain a given language line. Like the default language, the fallback language is also configured in the `config/app.php` configuration file:
41 |
42 | 'fallback_locale' => 'en',
43 |
44 |
45 | ## Basic Usage
46 |
47 | You may retrieve lines from language files using the `trans` helper function. The `trans` method accepts the file and key of the language line as its first argument. For example, let's retrieve the language line `welcome` in the `resources/lang/messages.php` language file:
48 |
49 | echo trans('messages.welcome');
50 |
51 | Of course if you are using the [Blade templating engine](/{{version}}/blade), you may use the `{{ }}` syntax to echo the language line:
52 |
53 | {{ trans('messages.welcome') }}
54 |
55 | If the specified language line does not exist, the `trans` function will simply return the language line key. So, using the example above, the `trans` function would return `messages.welcome` if the language line does not exist.
56 |
57 | #### Replacing Parameters In Language Lines
58 |
59 | If you wish, you may define place-holders in your language lines. All place-holders are prefixed with a `:`. For example, you may define a welcome message with a place-holder name:
60 |
61 | 'welcome' => 'Welcome, :name',
62 |
63 | To replace the place-holders when retrieving a language line, pass an array of replacements as the second argument to the `trans` function:
64 |
65 | echo trans('messages.welcome', ['name' => 'Dayle']);
66 |
67 |
68 | ### Pluralization
69 |
70 | Pluralization is a complex problem, as different languages have a variety of complex rules for pluralization. By using a "pipe" character, you may distinguish a singular and plural form of a string:
71 |
72 | 'apples' => 'There is one apple|There are many apples',
73 |
74 | Then, you may then use the `trans_choice` function to retrieve the line for a given "count". In this example, since the count is greater than one, the plural form of the language line is returned:
75 |
76 | echo trans_choice('messages.apples', 10);
77 |
78 | Since the Laravel translator is powered by the Symfony Translation component, you may create even more complex pluralization rules:
79 |
80 | 'apples' => '{0} There are none|[1,19] There are some|[20,Inf] There are many',
81 |
82 |
83 | ## Overriding Vendor Language Files
84 |
85 | Some packages may ship with their own language files. Instead of hacking the package's core files to tweak these lines, you may override them by placing your own files in the `resources/lang/vendor/{package}/{locale}` directory.
86 |
87 | So, for example, if you need to override the English language lines in `messages.php` for a package named `skyrim/hearthfire`, you would place a language file at: `resources/lang/vendor/hearthfire/en/messages.php`. In this file you should only define the language lines you wish to override. Any language lines you don't override will still be loaded from the package's original language files.
--------------------------------------------------------------------------------
/middleware.md:
--------------------------------------------------------------------------------
1 | # HTTP Middleware
2 |
3 | - [Introduction](#introduction)
4 | - [Defining Middleware](#defining-middleware)
5 | - [Registering Middleware](#registering-middleware)
6 | - [Middleware Parameters](#middleware-parameters)
7 | - [Terminable Middleware](#terminable-middleware)
8 |
9 |
10 | ## Introduction
11 |
12 | HTTP middleware provide a convenient mechanism for filtering HTTP requests entering your application. For example, Laravel includes a middleware that verifies the user of your application is authenticated. If the user is not authenticated, the middleware will redirect the user to the login screen. However, if the user is authenticated, the middleware will allow the request to proceed further into the application.
13 |
14 | Of course, additional middleware can be written to perform a variety of tasks besides authentication. A CORS middleware might be responsible for adding the proper headers to all responses leaving your application. A logging middleware might log all incoming requests to your application.
15 |
16 | There are several middleware included in the Laravel framework, including middleware for maintenance, authentication, CSRF protection, and more. All of these middleware are located in the `app/Http/Middleware` directory.
17 |
18 |
19 | ## Defining Middleware
20 |
21 | To create a new middleware, use the `make:middleware` Artisan command:
22 |
23 | php artisan make:middleware OldMiddleware
24 |
25 | This command will place a new `OldMiddleware` class within your `app/Http/Middleware` directory. In this middleware, we will only allow access to the route if the supplied `age` is greater than 200. Otherwise, we will redirect the users back to the "home" URI.
26 |
27 | input('age') <= 200) {
45 | return redirect('home');
46 | }
47 |
48 | return $next($request);
49 | }
50 |
51 | }
52 |
53 | As you can see, if the given `age` is less than or equal to `200`, the middleware will return an HTTP redirect to the client; otherwise, the request will be passed further into the application. To pass the request deeper into the application (allowing the middleware to "pass"), simply call the `$next` callback with the `$request`.
54 |
55 | It's best to envision middleware as a series of "layers" HTTP requests must pass through before they hit your application. Each layer can examine the request and even reject it entirely.
56 |
57 | ### *Before* / *After* Middleware
58 |
59 | Whether a middleware runs before or after a request depends on the middleware itself. For example, the following middleware would perform some task **before** the request is handled by the application:
60 |
61 |
98 | ## Registering Middleware
99 |
100 | ### Global Middleware
101 |
102 | If you want a middleware to be run during every HTTP request to your application, simply list the middleware class in the `$middleware` property of your `app/Http/Kernel.php` class.
103 |
104 | ### Assigning Middleware To Routes
105 |
106 | If you would like to assign middleware to specific routes, you should first assign the middleware a short-hand key in your `app/Http/Kernel.php` file. By default, the `$routeMiddleware` property of this class contains entries for the middleware included with Laravel. To add your own, simply append it to this list and assign it a key of your choosing. For example:
107 |
108 | // Within App\Http\Kernel Class...
109 |
110 | protected $routeMiddleware = [
111 | 'auth' => \App\Http\Middleware\Authenticate::class,
112 | 'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
113 | 'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
114 | ];
115 |
116 | Once the middleware has been defined in the HTTP kernel, you may use the `middleware` key in the route options array:
117 |
118 | Route::get('admin/profile', ['middleware' => 'auth', function () {
119 | //
120 | }]);
121 |
122 | Use an array to assign multiple middleware to the route:
123 |
124 | Route::get('/', ['middleware' => ['first', 'second'], function () {
125 | //
126 | }]);
127 |
128 | Instead of using an array, you may also chain the `middleware` method onto the route definition:
129 |
130 | Route::get('/', function () {
131 | //
132 | }])->middleware(['first', 'second']);
133 |
134 |
135 | ## Middleware Parameters
136 |
137 | Middleware can also receive additional custom parameters. For example, if your application needs to verify that the authenticated user has a given "role" before performing a given action, you could create a `RoleMiddleware` that receives a role name as an additional argument.
138 |
139 | Additional middleware parameters will be passed to the middleware after the `$next` argument:
140 |
141 | user()->hasRole($role)) {
160 | // Redirect...
161 | }
162 |
163 | return $next($request);
164 | }
165 |
166 | }
167 |
168 | Middleware parameters may be specified when defining the route by separating the middleware name and parameters with a `:`. Multiple parameters should be delimited by commas:
169 |
170 | Route::put('post/{id}', ['middleware' => 'role:editor', function ($id) {
171 | //
172 | }]);
173 |
174 |
175 | ## Terminable Middleware
176 |
177 | Sometimes a middleware may need to do some work after the HTTP response has already been sent to the browser. For example, the "session" middleware included with Laravel writes the session data to storage _after_ the response has been sent to the browser. To accomplish this, define the middleware as "terminable" by adding a `terminate` method to the middleware:
178 |
179 |
14 | ## Introduction
15 |
16 | Packages are the primary way of adding functionality to Laravel. Packages might be anything from a great way to work with dates like [Carbon](https://github.com/briannesbitt/Carbon), or an entire BDD testing framework like [Behat](https://github.com/Behat/Behat).
17 |
18 | Of course, there are different types of packages. Some packages are stand-alone, meaning they work with any framework, not just Laravel. Both Carbon and Behat are examples of stand-alone packages. Any of these packages may be used with Laravel by simply requesting them in your `composer.json` file.
19 |
20 | On the other hand, other packages are specifically intended for use with Laravel. These packages may have routes, controllers, views, and configuration specifically intended to enhance a Laravel application. This guide primarily covers the development of those packages that are Laravel specific.
21 |
22 |
23 | ## Service Providers
24 |
25 | [Service providers](/{{version}}/providers) are the connection points between your package and Laravel. A service provider is responsible for binding things into Laravel's [service container](/{{version}}/container) and informing Laravel where to load package resources such as views, configuration, and localization files.
26 |
27 | A service provider extends the `Illuminate\Support\ServiceProvider` class and contains two methods: `register` and `boot`. The base `ServiceProvider` class is located in the `illuminate/support` Composer package, which you should add to your own package's dependencies.
28 |
29 | To learn more about the structure and purpose of service providers, check out [their documentation](/{{version}}/providers).
30 |
31 |
32 | ## Routing
33 |
34 | To define routes for your package, simply `require` the routes file from within your package service provider's `boot` method. From within your routes file, you may use the `Route` facade to [register routes](/{{version}}/routing) just as you would within a typical Laravel application:
35 |
36 | /**
37 | * Perform post-registration booting of services.
38 | *
39 | * @return void
40 | */
41 | public function boot()
42 | {
43 | if (! $this->app->routesAreCached()) {
44 | require __DIR__.'/../../routes.php';
45 | }
46 | }
47 |
48 |
49 | ## Resources
50 |
51 |
52 | ### Views
53 |
54 | To register your package's [views](/{{version}}/views) with Laravel, you need to tell Laravel where the views are located. You may do this using the service provider's `loadViewsFrom` method. The `loadViewsFrom` method accepts two arguments: the path to your view templates and your package's name. For example, if your package name is "courier", add the following to your service provider's `boot` method:
55 |
56 | /**
57 | * Perform post-registration booting of services.
58 | *
59 | * @return void
60 | */
61 | public function boot()
62 | {
63 | $this->loadViewsFrom(__DIR__.'/path/to/views', 'courier');
64 | }
65 |
66 | Package views are referenced using a double-colon `package::view` syntax. So, you may load the `admin` view from the `courier` package like so:
67 |
68 | Route::get('admin', function () {
69 | return view('courier::admin');
70 | });
71 |
72 | #### Overriding Package Views
73 |
74 | When you use the `loadViewsFrom` method, Laravel actually registers **two** locations for your views: one in the application's `resources/views/vendor` directory and one in the directory you specify. So, using our `courier` example: when requesting a package view, Laravel will first check if a custom version of the view has been provided by the developer in `resources/views/vendor/courier`. Then, if the view has not been customized, Laravel will search the package view directory you specified in your call to `loadViewsFrom`. This makes it easy for end-users to customize / override your package's views.
75 |
76 | #### Publishing Views
77 |
78 | If you would like to make your views available for publishing to the application's `resources/views/vendor` directory, you may use the service provider's `publishes` method. The `publishes` method accepts an array of package view paths and their corresponding publish locations.
79 |
80 | /**
81 | * Perform post-registration booting of services.
82 | *
83 | * @return void
84 | */
85 | public function boot()
86 | {
87 | $this->loadViewsFrom(__DIR__.'/path/to/views', 'courier');
88 |
89 | $this->publishes([
90 | __DIR__.'/path/to/views' => base_path('resources/views/vendor/courier'),
91 | ]);
92 | }
93 |
94 | Now, when users of your package execute Laravel's `vendor:publish` Artisan command, your views package's will be copied to the specified location.
95 |
96 |
97 | ### Translations
98 |
99 | If your package contains [translation files](/{{version}}/localization), you may use the `loadTranslationsFrom` method to inform Laravel how to load them. For example, if your package is named "courier", you should add the following to your service provider's `boot` method:
100 |
101 | /**
102 | * Perform post-registration booting of services.
103 | *
104 | * @return void
105 | */
106 | public function boot()
107 | {
108 | $this->loadTranslationsFrom(__DIR__.'/path/to/translations', 'courier');
109 | }
110 |
111 | Package translations are referenced using a double-colon `package::file.line` syntax. So, you may load the `courier` package's `welcome` line from the `messages` file like so:
112 |
113 | echo trans('courier::messages.welcome');
114 |
115 | #### Publishing Translations
116 |
117 | If you would like to publish your package's translations to the application's `resources/lang/vendor` directory, you may use the service provider's `publishes` method. The `publishes` method accepts an array of package paths and their corresponding publish locations. For example, to the publish the translation files for our example `courier` package:
118 |
119 | /**
120 | * Perform post-registration booting of services.
121 | *
122 | * @return void
123 | */
124 | public function boot()
125 | {
126 | $this->loadTranslationsFrom(__DIR__.'/path/to/translations', 'courier');
127 |
128 | $this->publishes([
129 | __DIR__.'/path/to/translations' => base_path('resources/lang/vendor/courier'),
130 | ]);
131 | }
132 |
133 | Now, when users of your package execute Laravel's `vendor:publish` Artisan command, your package's translations will be published to the specified location.
134 |
135 |
136 | ### Configuration
137 |
138 | Typically, you will want to publish your package's configuration file to the application's own `config` directory. This will allow users of your package to easily override your default configuration options. To publish a configuration file, just use the `publishes` method from the `boot` method of your service provider:
139 |
140 | /**
141 | * Perform post-registration booting of services.
142 | *
143 | * @return void
144 | */
145 | public function boot()
146 | {
147 | $this->publishes([
148 | __DIR__.'/path/to/config/courier.php' => config_path('courier.php'),
149 | ]);
150 | }
151 |
152 | Now, when users of your package execute Laravel's `vendor:publish` command, your file will be copied to the specified location. Of course, once your configuration has been published, it can be accessed like any other configuration file:
153 |
154 | $value = config('courier.option');
155 |
156 | #### Default Package Configuration
157 |
158 | You may also choose to merge your own package configuration file with the application's copy. This allows your users to include only the options they actually want to override in the published copy of the configuration. To merge the configurations, use the `mergeConfigFrom` method within your service provider's `register` method:
159 |
160 | /**
161 | * Register bindings in the container.
162 | *
163 | * @return void
164 | */
165 | public function register()
166 | {
167 | $this->mergeConfigFrom(
168 | __DIR__.'/path/to/config/courier.php', 'courier'
169 | );
170 | }
171 |
172 |
173 | ## Public Assets
174 |
175 | Your packages may have assets such as JavaScript, CSS, and images. To publish these assets to the application's `public` directory, use the service provider's `publishes` method. In this example, we will also add a `public` asset group tag, which may be used to publish groups of related assets:
176 |
177 | /**
178 | * Perform post-registration booting of services.
179 | *
180 | * @return void
181 | */
182 | public function boot()
183 | {
184 | $this->publishes([
185 | __DIR__.'/path/to/assets' => public_path('vendor/courier'),
186 | ], 'public');
187 | }
188 |
189 | Now, when your package's users execute the `vendor:publish` command, your assets will be copied to the specified location. Since you typically will need to overwrite the assets every time the package is updated, you may use the `--force` flag:
190 |
191 | php artisan vendor:publish --tag=public --force
192 |
193 | If you would like to make sure your public assets are always up-to-date, you can add this command to the `post-update-cmd` list in your `composer.json` file.
194 |
195 |
196 | ## Publishing File Groups
197 |
198 | You may want to publish groups of package assets and resources separately. For instance, you might want your users to be able to publish your package's configuration files without being forced to publish your package's assets at the same time. You may do this by "tagging" them when calling the `publishes` method. For example, let's define two publish groups in the `boot` method of a package service provider:
199 |
200 | /**
201 | * Perform post-registration booting of services.
202 | *
203 | * @return void
204 | */
205 | public function boot()
206 | {
207 | $this->publishes([
208 | __DIR__.'/../config/package.php' => config_path('package.php')
209 | ], 'config');
210 |
211 | $this->publishes([
212 | __DIR__.'/../database/migrations/' => database_path('migrations')
213 | ], 'migrations');
214 | }
215 |
216 | Now your users may publish these groups separately by referencing their tag name when using the `vendor:publish` Artisan command:
217 |
218 | php artisan vendor:publish --provider="Vendor\Providers\PackageServiceProvider" --tag="config"
--------------------------------------------------------------------------------
/pagination.md:
--------------------------------------------------------------------------------
1 | # Paginación
2 |
3 | - [Introducción](#introduction)
4 | - [Uso básico](#basic-usage)
5 | - [Paginar resultado de una consulta](#paginating-query-builder-results)
6 | - [Paginar resultados de Eloquent](#paginating-eloquent-results)
7 | - [Paginar manualmente](#manually-creating-a-paginator)
8 | - [Mostrando resultado en una vista](#displaying-results-in-a-view)
9 | - [Convertir resultados a JSON](#converting-results-to-json)
10 |
11 |
12 | ## Introduction
13 |
14 | In other frameworks, pagination can be very painful. Laravel makes it a breeze. Laravel can quickly generate an intelligent "range" of links based on the current page, and the generated HTML is compatible with the [Bootstrap CSS framework](http://getbootstrap.com/).
15 |
16 |
17 | ## Basic Usage
18 |
19 |
20 | ### Paginating Query Builder Results
21 |
22 | There are several ways to paginate items. The simplest is by using the `paginate` method on the [query builder](/{{version}}/queries) or an [Eloquent query](/{{version}}/eloquent). The `paginate` method provided by Laravel automatically takes care of setting the proper limit and offset based on the current page being viewed by the user. By default, the current page is detected by the value of the `?page` query string argument on the HTTP request. Of course, this value is automatically detected by Laravel, and is also automatically inserted into links generated by the paginator.
23 |
24 | First, let's take a look at calling the `paginate` method on a query. In this example, the only argument passed to `paginate` is the number of items you would like displayed "per page". In this case, let's specify that we would like to display `15` items per page:
25 |
26 | paginate(15);
43 |
44 | return view('user.index', ['users' => $users]);
45 | }
46 | }
47 |
48 | > **Note:** Currently, pagination operations that use a `groupBy` statement cannot be executed efficiently by Laravel. If you need to use a `groupBy` with a paginated result set, it is recommended that you query the database and create a paginator manually.
49 |
50 | #### "Simple Pagination"
51 |
52 | If you only need to display simple "Next" and "Previous" links in your pagination view, you have the option of using the `simplePaginate` method to perform a more efficient query. This is very useful for large datasets if you do not need to display a link for each page number when rendering your view:
53 |
54 | $users = DB::table('users')->simplePaginate(15);
55 |
56 |
57 | ### Paginating Eloquent Results
58 |
59 | You may also paginate [Eloquent](/{{version}}/eloquent) queries. In this example, we will paginate the `User` model with `15` items per page. As you can see, the syntax is nearly identical to paginating query builder results:
60 |
61 | $users = App\User::paginate(15);
62 |
63 | Of course, you may call `paginate` after setting other constraints on the query, such as `where` clauses:
64 |
65 | $users = User::where('votes', '>', 100)->paginate(15);
66 |
67 | You may also use the `simplePaginate` method when paginating Eloquent models:
68 |
69 | $users = User::where('votes', '>', 100)->simplePaginate(15);
70 |
71 |
72 | ### Manually Creating A Paginator
73 |
74 | Sometimes you may wish to create a pagination instance manually, passing it an array of items. You may do so by creating either an `Illuminate\Pagination\Paginator` or `Illuminate\Pagination\LengthAwarePaginator` instance, depending on your needs.
75 |
76 | The `Paginator` class does not need to know the total number of items in the result set; however, because of this, the class does not have methods for retrieving the index of the last page. The `LengthAwarePaginator` accepts almost the same arguments as the `Paginator`; however, it does require a count of the total number of items in the result set.
77 |
78 | In other words, the `Paginator` corresponds to the `simplePaginate` method on the query builder and Eloquent, while the `LengthAwarePaginator` corresponds to the `paginate` method.
79 |
80 | When manually creating a paginator instance, you should manually "slice" the array of results you pass to the paginator. If you're unsure how to do this, check out the [array_slice](http://php.net/manual/en/function.array-slice.php) PHP function.
81 |
82 |
83 | ## Displaying Results In A View
84 |
85 | When you call the `paginate` or `simplePaginate` methods on a query builder or Eloquent query, you will receive a paginator instance. When calling the `paginate` method, you will receive an instance of `Illuminate\Pagination\LengthAwarePaginator`. When calling the `simplePaginate` method, you will receive an instance of `Illuminate\Pagination\Paginator`. These objects provide several methods that describe the result set. In addition to these helpers methods, the paginator instances are iterators and may be looped as an array.
86 |
87 | So, once you have retrieved the results, you may display the results and render the page links using [Blade](/{{version}}/blade):
88 |
89 |
90 | @foreach ($users as $user)
91 | {{ $user->name }}
92 | @endforeach
93 |
94 |
95 | {!! $users->render() !!}
96 |
97 | The `render` method will render the links to the rest of the pages in the result set. Each of these links will already contain the proper `?page` query string variable. Remember, the HTML generated by the `render` method is compatible with the [Bootstrap CSS framework](https://getbootstrap.com).
98 |
99 | > **Note:** When calling the `render` method from a Blade template, be sure to use the `{!! !!}` syntax so the HTML links are not escaped.
100 |
101 | #### Customizing The Paginator URI
102 |
103 | The `setPath` method allows you to customize the URI used by the paginator when generating links. For example, if you want the paginator to generate links like `http://example.com/custom/url?page=N`, you should pass `custom/url` to the `setPath` method:
104 |
105 | Route::get('users', function () {
106 | $users = App\User::paginate(15);
107 |
108 | $users->setPath('custom/url');
109 |
110 | //
111 | });
112 |
113 | #### Appending To Pagination Links
114 |
115 | You may add to the query string of pagination links using the `appends` method. For example, to append `&sort=votes` to each pagination link, you should make the following call to `appends`:
116 |
117 | {!! $users->appends(['sort' => 'votes'])->render() !!}
118 |
119 | If you wish to append a "hash fragment" to the paginator's URLs, you may use the `fragment` method. For example, to append `#foo` to the end of each pagination link, make the following call to the `fragment` method:
120 |
121 | {!! $users->fragment('foo')->render() !!}
122 |
123 | #### Additional Helper Methods
124 |
125 | You may also access additional pagination information via the following methods on paginator instances:
126 |
127 | - `$results->count()`
128 | - `$results->currentPage()`
129 | - `$results->hasMorePages()`
130 | - `$results->lastPage() (Not available when using simplePaginate)`
131 | - `$results->nextPageUrl()`
132 | - `$results->previousPageUrl()`
133 | - `$results->perPage()`
134 | - `$results->total() (Not available when using simplePaginate)`
135 | - `$results->url($page)`
136 |
137 |
138 | ## Converting Results To JSON
139 |
140 | The Laravel paginator result classes implement the `Illuminate\Contracts\Support\JsonableInterface` contract and expose the `toJson` method, so it's very easy to convert your pagination results to JSON.
141 |
142 | You may also convert a paginator instance to JSON by simply returning it from a route or controller action:
143 |
144 | Route::get('users', function () {
145 | return App\User::paginate();
146 | });
147 |
148 | The JSON from the paginator will include meta information such as `total`, `current_page`, `last_page`, and more. The actual result objects will be available via the `data` key in the JSON array. Here is an example of the JSON created by returning a paginator instance from a route:
149 |
150 | #### Example Paginator JSON
151 |
152 | {
153 | "total": 50,
154 | "per_page": 15,
155 | "current_page": 1,
156 | "last_page": 4,
157 | "next_page_url": "http://laravel.app?page=2",
158 | "prev_page_url": null,
159 | "from": 1,
160 | "to": 15,
161 | "data":[
162 | {
163 | // Result Object
164 | },
165 | {
166 | // Result Object
167 | }
168 | ]
169 | }
--------------------------------------------------------------------------------
/providers.md:
--------------------------------------------------------------------------------
1 | # Service Providers
2 |
3 | - [Introduction](#introduction)
4 | - [Writing Service Providers](#writing-service-providers)
5 | - [The Register Method](#the-register-method)
6 | - [The Boot Method](#the-boot-method)
7 | - [Registering Providers](#registering-providers)
8 | - [Deferred Providers](#deferred-providers)
9 |
10 |
11 | ## Introduction
12 |
13 | Service providers are the central place of all Laravel application bootstrapping. Your own application, as well as all of Laravel's core services are bootstrapped via service providers.
14 |
15 | But, what do we mean by "bootstrapped"? In general, we mean **registering** things, including registering service container bindings, event listeners, middleware, and even routes. Service providers are the central place to configure your application.
16 |
17 | If you open the `config/app.php` file included with Laravel, you will see a `providers` array. These are all of the service provider classes that will be loaded for your application. Of course, many of them are "deferred" providers, meaning they will not be loaded on every request, but only when the services they provide are actually needed.
18 |
19 | In this overview you will learn how to write your own service providers and register them with your Laravel application.
20 |
21 |
22 | ## Writing Service Providers
23 |
24 | All service providers extend the `Illuminate\Support\ServiceProvider` class. This abstract class requires that you define at least one method on your provider: `register`. Within the `register` method, you should **only bind things into the [service container](/{{version}}/container)**. You should never attempt to register any event listeners, routes, or any other piece of functionality within the `register` method.
25 |
26 | The Artisan CLI can easily generate a new provider via the `make:provider` command:
27 |
28 | php artisan make:provider RiakServiceProvider
29 |
30 |
31 | ### The Register Method
32 |
33 | As mentioned previously, within the `register` method, you should only bind things into the [service container](/{{version}}/container). You should never attempt to register any event listeners, routes, or any other piece of functionality within the `register` method. Otherwise, you may accidently use a service that is provided by a service provider which has not loaded yet.
34 |
35 | Now, let's take a look at a basic service provider:
36 |
37 | app->singleton('Riak\Contracts\Connection', function ($app) {
54 | return new Connection(config('riak'));
55 | });
56 | }
57 | }
58 |
59 | This service provider only defines a `register` method, and uses that method to define an implementation of `Riak\Contracts\Connection` in the service container. If you don't understand how the service container works, check out [its documentation](/{{version}}/container).
60 |
61 |
62 | ### The Boot Method
63 |
64 | So, what if we need to register a view composer within our service provider? This should be done within the `boot` method. **This method is called after all other service providers have been registered**, meaning you have access to all other services that have been registered by the framework:
65 |
66 | composer('view', function () {
82 | //
83 | });
84 | }
85 |
86 | /**
87 | * Register bindings in the container.
88 | *
89 | * @return void
90 | */
91 | public function register()
92 | {
93 | //
94 | }
95 | }
96 |
97 | #### Boot Method Dependency Injection
98 |
99 | We are able to type-hint dependencies for our `boot` method. The [service container](/{{version}}/container) will automatically inject any dependencies you need:
100 |
101 | use Illuminate\Contracts\Routing\ResponseFactory;
102 |
103 | public function boot(ResponseFactory $factory)
104 | {
105 | $factory->macro('caps', function ($value) {
106 | //
107 | });
108 | }
109 |
110 |
111 | ## Registering Providers
112 |
113 | All service providers are registered in the `config/app.php` configuration file. This file contains a `providers` array where you can list the names of your service providers. By default, a set of Laravel core service providers are listed in this array. These providers bootstrap the core Laravel components, such as the mailer, queue, cache, and others.
114 |
115 | To register your provider, simply add it to the array:
116 |
117 | 'providers' => [
118 | // Other Service Providers
119 |
120 | 'App\Providers\AppServiceProvider',
121 | ],
122 |
123 |
124 | ## Deferred Providers
125 |
126 | If your provider is **only** registering bindings in the [service container](/{{version}}/container), you may choose to defer its registration until one of the registered bindings is actually needed. Deferring the loading of such a provider will improve the performance of your application, since it is not loaded from the filesystem on every request.
127 |
128 | To defer the loading of a provider, set the `defer` property to `true` and define a `provides` method. The `provides` method returns the service container bindings that the provider registers:
129 |
130 | app->singleton('Riak\Contracts\Connection', function ($app) {
154 | return new Connection($app['config']['riak']);
155 | });
156 | }
157 |
158 | /**
159 | * Get the services provided by the provider.
160 | *
161 | * @return array
162 | */
163 | public function provides()
164 | {
165 | return ['Riak\Contracts\Connection'];
166 | }
167 |
168 | }
169 |
170 | Laravel compiles and stores a list of all of the services supplied by deferred service providers, along with the name of its service provider class. Then, only when you attempt to resolve one of these services does Laravel load the service provider.
171 |
--------------------------------------------------------------------------------
/readme.md:
--------------------------------------------------------------------------------
1 | # Documentación de Laravel PHP Framework en Español
2 |
3 | Repositorio con la documentación de Laravel PHP Framework en Español, actualmente se soporta la versión 4.1, 5.0 y 5.1.
4 |
5 | Puedes verla funcionando en:
6 | https://laravel.montogeek.com/
7 |
8 | [](https://snap-ci.com/montogeek/laravel-docs-es/branch/master)
9 |
--------------------------------------------------------------------------------
/redis.md:
--------------------------------------------------------------------------------
1 | # Redis
2 |
3 | - [Introducción](#introduction)
4 | - [Uso basico](#basic-usage)
5 | - [Pipelining Commands](#pipelining-commands)
6 | - [Pub / Sub](#pubsub)
7 |
8 |
9 | ## Introducción
10 |
11 | [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 Redis with Laravel, you will need to install the `predis/predis` package (~1.0) via Composer.
12 |
13 |
14 | ### Configuration
15 |
16 | The Redis configuration for your application is located in the `config/database.php` configuration file. Within this file, you will see a `redis` array containing the Redis servers used by your application:
17 |
18 | 'redis' => [
19 |
20 | 'cluster' => false,
21 |
22 | 'default' => [
23 | 'host' => '127.0.0.1',
24 | 'port' => 6379,
25 | 'database' => 0,
26 | ],
27 |
28 | ],
29 |
30 | The default server configuration should suffice for development. However, you are free to modify this array based on your environment. Simply give each Redis server a name, and specify the host and port used by the server.
31 |
32 | The `cluster` option will tell the Laravel Redis client to perform client-side sharding across your Redis nodes, allowing you to pool nodes and create a large amount of available RAM. However, note that client-side sharding does not handle failover; therefore, is primarily suited for cached data that is available from another primary data store.
33 |
34 | Additionally, you may define an `options` array value in your Redis connection definition, allowing you to specify a set of Predis [client options](https://github.com/nrk/predis/wiki/Client-Options).
35 |
36 | If your Redis server requires authentication, you may supply a password by adding a `password` configuration item to your Redis server configuration array.
37 |
38 | > **Note:** If you have the Redis PHP extension installed via PECL, you will need to rename the alias for Redis in your `config/app.php` file.
39 |
40 |
41 | ## Uso basico
42 |
43 | You may interact with Redis by calling various methods on the `Redis` [facade](/{{version}}/facades). The `Redis` facade supports dynamic methods, meaning you may call any [Redis command](http://redis.io/commands) on the facade and the command will be passed directly to Redis. In this example, we will call the `GET` command on Redis by calling the `get` method on the `Redis` facade:
44 |
45 | $user]);
65 | }
66 | }
67 |
68 | Of course, as mentioned above, you may call any of the Redis commands on the `Redis` facade. Laravel uses magic methods to pass the commands to the Redis server, so simply pass the arguments the Redis command expects:
69 |
70 | Redis::set('name', 'Taylor');
71 |
72 | $values = Redis::lrange('names', 5, 10);
73 |
74 | Alternatively, you may also pass commands to the server using the `command` method, which accepts the name of the command as its first argument, and an array of values as its second argument:
75 |
76 | $values = Redis::command('lrange', ['name', 5, 10]);
77 |
78 | #### Using Multiple Redis Connections
79 |
80 | You may get a Redis instance by calling the `Redis::connection` method:
81 |
82 | $redis = Redis::connection();
83 |
84 | This will give you an instance of the default Redis server. If you are not using server clustering, you may pass the server name to the `connection` method to get a specific server as defined in your Redis configuration:
85 |
86 | $redis = Redis::connection('other');
87 |
88 |
89 | ### Pipelining Commands
90 |
91 | Pipelining should be used when you need to send many commands to the server in one operation. The `pipeline` method accepts one argument: a `Closure` that receives a Redis instance. You may issue all of your commands to this Redis instance and they will all be executed within a single operation:
92 |
93 | Redis::pipeline(function ($pipe) {
94 | for ($i = 0; $i < 1000; $i++) {
95 | $pipe->set("key:$i", $i);
96 | }
97 | });
98 |
99 |
100 | ## Pub / Sub
101 |
102 | Laravel also provides a convenient interface to the Redis `publish` and `subscribe` commands. These Redis commands allow you to listen for messages on a given "channel". You may publish messages to the channel from another application, or even using another programming language, allowing easy communication between applications / processes.
103 |
104 | First, let's setup a listener on a channel via Redis using the `subscribe` method. We will place this method call within an [Artisan command](/{{version}}/artisan) since calling the `subscribe` method begins a long-running process:
105 |
106 | 'bar']));
148 | });
149 |
150 | #### Wildcard Subscriptions
151 |
152 | Using the `psubscribe` method, you may subscribe to a wildcard channel, which is useful for catching all messages on all channels. The `$channel` name will be passed as the second argument to the provided callback `Closure`:
153 |
154 | Redis::psubscribe(['*'], function($message, $channel) {
155 | echo $message;
156 | });
157 |
158 | Redis::psubscribe(['users.*'], function($message, $channel) {
159 | echo $message;
160 | });
161 |
--------------------------------------------------------------------------------
/requests.md:
--------------------------------------------------------------------------------
1 | # HTTP Requests
2 |
3 | - [Accessing The Request](#accessing-the-request)
4 | - [Basic Request Information](#basic-request-information)
5 | - [PSR-7 Requests](#psr7-requests)
6 | - [Retrieving Input](#retrieving-input)
7 | - [Old Input](#old-input)
8 | - [Cookies](#cookies)
9 | - [Files](#files)
10 |
11 |
12 | ## Accessing The Request
13 |
14 | To obtain an instance of the current HTTP request via dependency injection, you should type-hint the `Illuminate\Http\Request` class on your controller constructor or method. The current request instance will automatically be injected by the [service container](/{{version}}/container):
15 |
16 | input('name');
34 |
35 | //
36 | }
37 | }
38 |
39 | If your controller method is also expecting input from a route parameter, simply list your route arguments after your other dependencies. For example, if your route is defined like so:
40 |
41 | Route::put('user/{id}', 'UserController@update');
42 |
43 | You may still type-hint the `Illuminate\Http\Request` and access your route parameter `id` by defining your controller method like the following:
44 |
45 |
68 | ### Basic Request Information
69 |
70 | The `Illuminate\Http\Request` instance provides a variety of methods for examining the HTTP request for your application. The Laravel `Illuminate\Http\Request` extends the `Symfony\Component\HttpFoundation\Request` class. Here are a few more of the useful methods available on this class:
71 |
72 | #### Retrieving The Request URI
73 |
74 | The `path` method returns the request's URI. So, if the incoming request is targeted at `http://domain.com/foo/bar`, the `path` method will return `foo/bar`:
75 |
76 | $uri = $request->path();
77 |
78 | The `is` method allows you to verify that the incoming request URI matches a given pattern. You may use the `*` character as a wildcard when utilizing this method:
79 |
80 | if ($request->is('admin/*')) {
81 | //
82 | }
83 |
84 | To get the full URL, not just the path info, you may use the `url` method on the request instance:
85 |
86 | $url = $request->url();
87 |
88 | #### Retrieving The Request Method
89 |
90 | The `method` method will return the HTTP verb for the request. You may also use the `isMethod` method to verify that the HTTP verb matches a given string:
91 |
92 | $method = $request->method();
93 |
94 | if ($request->isMethod('post')) {
95 | //
96 | }
97 |
98 |
99 | ### PSR-7 Requests
100 |
101 | The PSR-7 standard specifies interfaces for HTTP messages, including requests and responses. If you would like to obtain an instance of a PSR-7 request, you will first need to install a few libraries. Laravel uses the Symfony HTTP Message Bridge component to convert typical Laravel requests and responses into PSR-7 compatible implementations:
102 |
103 | composer require symfony/psr-http-message-bridge
104 |
105 | composer require zendframework/zend-diactoros
106 |
107 | Once you have installed these libraries, you may obtain a PSR-7 request by simply type-hinting the request type on your route or controller:
108 |
109 | use Psr\Http\Message\ServerRequestInterface;
110 |
111 | Route::get('/', function (ServerRequestInterface $request) {
112 | //
113 | });
114 |
115 | If you return a PSR-7 response instance from a route or controller, it will automatically be converted back to a Laravel response instance and be displayed by the framework.
116 |
117 |
118 | ## Retrieving Input
119 |
120 | #### Retrieving An Input Value
121 |
122 | Using a few simple methods, you may access all user input from your `Illuminate\Http\Request` instance. 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:
123 |
124 | $name = $request->input('name');
125 |
126 | Alternatively, you may access user input using the properties of the `Illuminate\Http\Request` instance. For example, if one of your application's forms contains a `name` field, you may access the value of the posted field like so:
127 |
128 | $name = $request->name;
129 |
130 | You may pass a default value as the second argument to the `input` method. This value will be returned if the requested input value is not present on the request:
131 |
132 | $name = $request->input('name', 'Sally');
133 |
134 | When working on forms with array inputs, you may use "dot" notation to access the arrays:
135 |
136 | $input = $request->input('products.0.name');
137 |
138 | #### Determining If An Input Value Is Present
139 |
140 | To determine if a value is present on the request, you may use the `has` method. The `has` method returns `true` if the value is present **and** is not an empty string:
141 |
142 | if ($request->has('name')) {
143 | //
144 | }
145 |
146 | #### Retrieving All Input Data
147 |
148 | You may also retrieve all of the input data as an `array` using the `all` method:
149 |
150 | $input = $request->all();
151 |
152 | #### Retrieving A Portion Of The Input Data
153 |
154 | If you need to retrieve a sub-set of the input data, you may use the `only` and `except` methods. Both of these methods will accept a single `array` or a dynamic list of arguments:
155 |
156 | $input = $request->only(['username', 'password']);
157 |
158 | $input = $request->only('username', 'password');
159 |
160 | $input = $request->except(['credit_card']);
161 |
162 | $input = $request->except('credit_card');
163 |
164 |
165 | ### Old Input
166 |
167 | Laravel allows you to keep input from one request during the next request. This feature is particularly useful for re-populating forms after detecting validation errors. However, if you are using Laravel's included [validation services](/{{version}}/validation), it is unlikely you will need to manually use these methods, as some of Laravel's built-in validation facilities will call them automatically.
168 |
169 | #### Flashing Input To The Session
170 |
171 | The `flash` method on the `Illuminate\Http\Request` instance will flash the current input to the [session](/{{version}}/session) so that it is available during the user's next request to the application:
172 |
173 | $request->flash();
174 |
175 | You may also use the `flashOnly` and `flashExcept` methods to flash a sub-set of the request data into the session:
176 |
177 | $request->flashOnly('username', 'email');
178 |
179 | $request->flashExcept('password');
180 |
181 | #### Flash Input Into Session Then Redirect
182 |
183 | Since you often will want to flash input in association with a redirect to the previous page, you may easily chain input flashing onto a redirect using the `withInput` method:
184 |
185 | return redirect('form')->withInput();
186 |
187 | return redirect('form')->withInput($request->except('password'));
188 |
189 | #### Retrieving Old Data
190 |
191 | To retrieve flashed input from the previous request, use the `old` method on the `Request` instance. The `old` method provides a convenient helper for pulling the flashed input data out of the [session](/{{version}}/session):
192 |
193 | $username = $request->old('username');
194 |
195 | Laravel also provides a global `old` helper function. If you are displaying old input within a [Blade template](/{{version}}/blade), it is more convenient to use the `old` helper:
196 |
197 | {{ old('username') }}
198 |
199 |
200 | ### Cookies
201 |
202 | #### Retrieving Cookies From The Request
203 |
204 | 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. To retrieve a cookie value from the request, you may use the `cookie` method on the `Illuminate\Http\Request` instance:
205 |
206 | $value = $request->cookie('name');
207 |
208 | #### Attaching A New Cookie To A Response
209 |
210 | Laravel provides a global `cookie` helper function which serves as a simple factory for generating new `Symfony\Component\HttpFoundation\Cookie` instances. The cookies may be attached to a `Illuminate\Http\Response` instance using the `withCookie` method:
211 |
212 | $response = new Illuminate\Http\Response('Hello World');
213 |
214 | $response->withCookie(cookie('name', 'value', $minutes));
215 |
216 | return $response;
217 |
218 | To create a long-lived cookie, which lasts for five years, you may use the `forever` method on the cookie factory by first calling the `cookie` helper with no arguments, and then chaining the `forever` method onto the returned cookie factory:
219 |
220 | $response->withCookie(cookie()->forever('name', 'value'));
221 |
222 |
223 | ### Files
224 |
225 | #### Retrieving Uploaded Files
226 |
227 | You may access uploaded files that are included with the `Illuminate\Http\Request` instance using the `file` method. 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:
228 |
229 | $file = $request->file('photo');
230 |
231 | #### Verifying File Presence
232 |
233 | You may also determine if a file is present on the request using the `hasFile` method:
234 |
235 | if ($request->hasFile('photo')) {
236 | //
237 | }
238 |
239 | #### Validating Successful Uploads
240 |
241 | In addition to checking if the file is present, you may verify that there were no problems uploading the file via the `isValid` method:
242 |
243 | if ($request->file('photo')->isValid()) {
244 | //
245 | }
246 |
247 | #### Moving Uploaded Files
248 |
249 | To move the uploaded file to a new location, you should use the `move` method. This method will move the file from its temporary upload location (as determined by your PHP configuration) to a more permanent destination of your choosing:
250 |
251 | $request->file('photo')->move($destinationPath);
252 |
253 | $request->file('photo')->move($destinationPath, $fileName);
254 |
255 | #### Other File Methods
256 |
257 | There are a variety of other methods available on `UploadedFile` instances. Check out the [API documentation for the class](http://api.symfony.com/2.7/Symfony/Component/HttpFoundation/File/UploadedFile.html) for more information regarding these methods.
--------------------------------------------------------------------------------
/responses.md:
--------------------------------------------------------------------------------
1 | # HTTP Responses
2 |
3 | - [Basic Responses](#basic-responses)
4 | - [Attaching Headers To Responses](#attaching-headers-to-responses)
5 | - [Attaching Cookies To Responses](#attaching-cookies-to-responses)
6 | - [Other Response Types](#other-response-types)
7 | - [View Responses](#view-responses)
8 | - [JSON Responses](#json-responses)
9 | - [File Downloads](#file-downloads)
10 | - [Redirects](#redirects)
11 | - [Redirecting To Named Routes](#redirecting-named-routes)
12 | - [Redirecting To Controller Actions](#redirecting-controller-actions)
13 | - [Redirecting With Flashed Session Data](#redirecting-with-flashed-session-data)
14 | - [Response Macros](#response-macros)
15 |
16 |
17 | ## Basic Responses
18 |
19 | Of course, all routes and controllers should return some kind of response to be sent back to the user's browser. Laravel provides several different ways to return responses. The most basic response is simply returning a string from a route or controller:
20 |
21 | Route::get('/', function () {
22 | return 'Hello World';
23 | });
24 |
25 | The given string will automatically be converted into an HTTP response by the framework.
26 |
27 | However, for most routes and controller actions, you will be returning a full `Illuminate\Http\Response` instance or a [view](/{{version}}/views). Returning a full `Response` instance allows you to customize the response's HTTP status code and headers. A `Response` instance inherits from the `Symfony\Component\HttpFoundation\Response` class, providing a variety of methods for building HTTP responses:
28 |
29 | use Illuminate\Http\Response;
30 |
31 | Route::get('home', function () {
32 | return (new Response($content, $status))
33 | ->header('Content-Type', $value);
34 | });
35 |
36 | For convenience, you may also use the `response` helper:
37 |
38 | Route::get('home', function () {
39 | return response($content, $status)
40 | ->header('Content-Type', $value);
41 | });
42 |
43 | > **Note:** For a full list of available `Response` methods, check out its [API documentation](http://laravel.com/api/master/Illuminate/Http/Response.html) and the [Symfony API documentation](http://api.symfony.com/2.7/Symfony/Component/HttpFoundation/Response.html).
44 |
45 |
46 | #### Attaching Headers To Responses
47 |
48 | Keep in mind that most response methods are chainable, allowing for the fluent building of responses. For example, you may use the `header` method to add a series of headers to the response before sending it back to the user:
49 |
50 | return response($content)
51 | ->header('Content-Type', $type)
52 | ->header('X-Header-One', 'Header Value')
53 | ->header('X-Header-Two', 'Header Value');
54 |
55 |
56 |
57 | #### Attaching Cookies To Responses
58 |
59 | The `withCookie` helper method on the response instance allows you to easily attach cookies to the response. For example, you may use the `withCookie` method to generate a cookie and attach it to the response instance:
60 |
61 | return response($content)->header('Content-Type', $type)
62 | ->withCookie('name', 'value');
63 |
64 | The `withCookie` method accepts additional optional arguments which allow you to further customize your cookie's properties:
65 |
66 | ->withCookie($name, $value, $minutes, $path, $domain, $secure, $httpOnly)
67 |
68 | By default, all cookies generated by Laravel are encrypted and signed so that they can't be modified or read by the client. If you would like to disable encryption for a certain subset of cookies generated by your application, you may use the `$except` property of the `App\Http\Middleware\EncryptCookies` middleware:
69 |
70 | /**
71 | * The names of the cookies that should not be encrypted.
72 | *
73 | * @var array
74 | */
75 | protected $except = [
76 | 'cookie_name',
77 | ];
78 |
79 |
80 | ## Other Response Types
81 |
82 | The `response` helper may be used to conveniently generate other types of response instances. When the `response` helper is called without arguments, an implementation of the `Illuminate\Contracts\Routing\ResponseFactory` [contract](/{{version}}/contracts) is returned. This contract provides several helpful methods for generating responses.
83 |
84 |
85 | #### View Responses
86 |
87 | If you need control over the response status and headers, but also need to return a [view](/{{version}}/views) as the response content, you may use the `view` method:
88 |
89 | return response()->view('hello', $data)->header('Content-Type', $type);
90 |
91 | Of course, if you do not need to pass a custom HTTP status code or custom headers, you may simply use the global `view` helper function.
92 |
93 |
94 | #### JSON Responses
95 |
96 | The `json` method will automatically set the `Content-Type` header to `application/json`, as well as convert the given array into JSON using the `json_encode` PHP function:
97 |
98 | return response()->json(['name' => 'Abigail', 'state' => 'CA']);
99 |
100 | If you would like to create a JSONP response, you may use the `json` method in addition to `setCallback`:
101 |
102 | return response()->json(['name' => 'Abigail', 'state' => 'CA'])
103 | ->setCallback($request->input('callback'));
104 |
105 |
106 | #### File Downloads
107 |
108 | The `download` method may be used to generate a response that forces the user's browser to download the file at the given path. The `download` method accepts a file name as the second argument to the method, which will determine the file name that is seen by the user downloading the file. Finally, you may pass an array of HTTP headers as the third argument to the method:
109 |
110 | return response()->download($pathToFile);
111 |
112 | return response()->download($pathToFile, $name, $headers);
113 |
114 | > **Note:** Symfony HttpFoundation, which manages file downloads, requires the file being downloaded to have an ASCII file name.
115 |
116 |
117 | ## Redirects
118 |
119 | Redirect responses are instances of the `Illuminate\Http\RedirectResponse` class, and contain the proper headers needed to redirect the user to another URL. There are several ways to generate a `RedirectResponse` instance. The simplest method is to use the global `redirect` helper method:
120 |
121 | Route::get('dashboard', function () {
122 | return redirect('home/dashboard');
123 | });
124 |
125 | Sometimes you may wish to redirect the user to their previous location, for example, after a form submission that is invalid. You may do so by using the global `back` helper function:
126 |
127 | Route::post('user/profile', function () {
128 | // Validate the request...
129 |
130 | return back()->withInput();
131 | });
132 |
133 |
134 | #### Redirecting To Named Routes
135 |
136 | When you call the `redirect` helper with no parameters, an instance of `Illuminate\Routing\Redirector` is returned, allowing you to call any method on the `Redirector` instance. For example, to generate a `RedirectResponse` to a named route, you may use the `route` method:
137 |
138 | return redirect()->route('login');
139 |
140 | If your route has parameters, you may pass them as the second argument to the `route` method:
141 |
142 | // For a route with the following URI: profile/{id}
143 |
144 | return redirect()->route('profile', [1]);
145 |
146 | If you are redirecting to a route with an "ID" parameter that is being populated from an Eloquent model, you may simply pass the model itself. The ID will be extracted automatically:
147 |
148 | return redirect()->route('profile', [$user]);
149 |
150 |
151 | #### Redirecting To Controller Actions
152 |
153 | You may also generate redirects to [controller actions](/{{version}}/controllers). To do so, simply pass the controller and action name to the `action` method. Remember, you do not need to specify the full namespace to the controller since Laravel's `RouteServiceProvider` will automatically set the default controller namespace:
154 |
155 | return redirect()->action('HomeController@index');
156 |
157 | Of course, if your controller route requires parameters, you may pass them as the second argument to the `action` method:
158 |
159 | return redirect()->action('UserController@profile', [1]);
160 |
161 |
162 | #### Redirecting With Flashed Session Data
163 |
164 | Redirecting to a new URL and [flashing data to the session](/{{version}}/session#flash-data) are typically done at the same time. So, for convenience, you may create a `RedirectResponse` instance **and** flash data to the session in a single method chain. This is particularly convenient for storing status messages after an action:
165 |
166 | Route::post('user/profile', function () {
167 | // Update the user's profile...
168 |
169 | return redirect('dashboard')->with('status', 'Profile updated!');
170 | });
171 |
172 | Of course, after the user is redirected to a new page, you may retrieve and display the flashed message from the [session](/{{version}}/session). For example, using [Blade syntax](/{{version}}/blade):
173 |
174 | @if (session('status'))
175 |
176 | {{ session('status') }}
177 |
178 | @endif
179 |
180 |
181 | ## Response Macros
182 |
183 | If you would like to define a custom response that you can re-use in a variety of your routes and controllers, you may use the `macro` method on an implementation of `Illuminate\Contracts\Routing\ResponseFactory`.
184 |
185 | For example, from a [service provider's](/{{version}}/providers) `boot` method:
186 |
187 | macro('caps', function ($value) use ($factory) {
205 | return $factory->make(strtoupper($value));
206 | });
207 | }
208 | }
209 |
210 | The `macro` function accepts a name as its first argument, and a Closure as its second. The macro's Closure will be executed when calling the macro name from a `ResponseFactory` implementation or the `response` helper:
211 |
212 | return response()->caps('foo');
213 |
--------------------------------------------------------------------------------
/scheduling.md:
--------------------------------------------------------------------------------
1 | # Task Scheduling
2 |
3 | - [Introduction](#introduction)
4 | - [Defining Schedules](#defining-schedules)
5 | - [Schedule Frequency Options](#schedule-frequency-options)
6 | - [Preventing Task Overlaps](#preventing-task-overlaps)
7 | - [Task Output](#task-output)
8 | - [Task Hooks](#task-hooks)
9 |
10 |
11 | ## Introduction
12 |
13 | In the past, developers have generated a Cron entry for each task they need to schedule. However, this is a headache. Your task schedule is no longer in source control, and you must SSH into your server to add the Cron entries. The Laravel command scheduler allows you to fluently and expressively define your command schedule within Laravel itself, and only a single Cron entry is needed on your server.
14 |
15 | Your task schedule is defined in the `app/Console/Kernel.php` file's `schedule` method. To help you get started, a simple example is included with the method. You are free to add as many scheduled tasks as you wish to the `Schedule` object.
16 |
17 | ### Starting The Scheduler
18 |
19 | Here is the only Cron entry you need to add to your server:
20 |
21 | * * * * * php /path/to/artisan schedule:run >> /dev/null 2>&1
22 |
23 | This Cron will call the Laravel command scheduler every minute. Then, Laravel evaluates your scheduled tasks and runs the tasks that are due.
24 |
25 |
26 | ## Defining Schedules
27 |
28 | You may define all of your scheduled tasks in the `schedule` method of the `App\Console\Kernel` class. To get started, let's look at an example of scheduling a task. In this example, we will schedule a `Closure` to be called every day at midnight. Within the `Closure` we will execute a database query to clear a table:
29 |
30 | call(function () {
58 | DB::table('recent_users')->delete();
59 | })->daily();
60 | }
61 | }
62 |
63 | In addition to scheduling `Closure` calls, you may also schedule [Artisan commands](/{{version}}/artisan) and operating system commands. For example, you may use the `command` method to schedule an Artisan command:
64 |
65 | $schedule->command('emails:send --force')->daily();
66 |
67 | The `exec` command may be used to issue a command to the operating system:
68 |
69 | $schedule->exec('node /home/forge/script.js')->daily();
70 |
71 |
72 | ### Schedule Frequency Options
73 |
74 | Of course, there are a variety of schedules you may assign to your task:
75 |
76 | Method | Description
77 | ------------- | -------------
78 | `->cron('* * * * *');` | Run the task on a custom Cron schedule
79 | `->everyMinute();` | Run the task every minute
80 | `->everyFiveMinutes();` | Run the task every five minutes
81 | `->everyTenMinutes();` | Run the task every ten minutes
82 | `->everyThirtyMinutes();` | Run the task every thirty minutes
83 | `->hourly();` | Run the task every hour
84 | `->daily();` | Run the task every day at midnight
85 | `->dailyAt('13:00');` | Run the task every day at 13:00
86 | `->twiceDaily(1, 13);` | Run the task daily at 1:00 & 13:00
87 | `->weekly();` | Run the task every week
88 | `->monthly();` | Run the task every month
89 | `->yearly();` | Run the task every year
90 |
91 | These methods may be combined with additional constraints to create even more finely tuned schedules that only run on certain days of the week. For example, to schedule a command to run weekly on Monday:
92 |
93 | $schedule->call(function () {
94 | // Runs once a week on Monday at 13:00...
95 | })->weekly()->mondays()->at('13:00');
96 |
97 | Below is a list of the additional schedule constraints:
98 |
99 | Method | Description
100 | ------------- | -------------
101 | `->weekdays();` | Limit the task to weekdays
102 | `->sundays();` | Limit the task to Sunday
103 | `->mondays();` | Limit the task to Monday
104 | `->tuesdays();` | Limit the task to Tuesday
105 | `->wednesdays();` | Limit the task to Wednesday
106 | `->thursdays();` | Limit the task to Thursday
107 | `->fridays();` | Limit the task to Friday
108 | `->saturdays();` | Limit the task to Saturday
109 | `->when(Closure);` | Limit the task based on a truth test
110 |
111 | #### Truth Test Constraints
112 |
113 | The `when` method may be used to limit the execution of a task based on the result of a given truth test. In other words, if the given `Closure` return `true`, the task will execute as long as no other constraining conditions prevent the task from running:
114 |
115 | $schedule->command('emails:send')->daily()->when(function () {
116 | return true;
117 | });
118 |
119 |
120 | ### Preventing Task Overlaps
121 |
122 | By default, scheduled tasks will be run even if the previous instance of the task is still running. To prevent this, you may use the `withoutOverlapping` method:
123 |
124 | $schedule->command('emails:send')->withoutOverlapping();
125 |
126 | In this example, the `emails:send` [Artisan command](/{{version}}/artisan) will be run every minute if it is not already running. The `withoutOverlapping` method is especially useful if you have tasks that vary drastically in their execution time, preventing you from predicting exactly how long a given task will take.
127 |
128 |
129 | ## Task Output
130 |
131 | The Laravel scheduler provides several convenient methods for working with the output generated by scheduled tasks. First, using the `sendOutputTo` method, you may send the output to a file for later inspection:
132 |
133 | $schedule->command('emails:send')
134 | ->daily()
135 | ->sendOutputTo($filePath);
136 |
137 | If you would like to append the output to a given file, you may use the `appendOutputTo` method:
138 |
139 | $schedule->command('emails:send')
140 | ->daily()
141 | ->appendOutputTo($filePath);
142 |
143 | Using the `emailOutputTo` method, you may e-mail the output to an e-mail address of your choice. Note that the output must first be sent to a file using the `sendOutputTo` method. Also, before e-mailing the output of a task, you should configure Laravel's [e-mail services](/{{version}}/mail):
144 |
145 | $schedule->command('foo')
146 | ->daily()
147 | ->sendOutputTo($filePath)
148 | ->emailOutputTo('foo@example.com');
149 |
150 | > **Note:** The `emailOutputTo` and `sendOutputTo` methods are exclusive to the `command` method and are not supported for `call`.
151 |
152 |
153 | ## Task Hooks
154 |
155 | Using the `before` and `after` methods, you may specify code to be executed before and after the scheduled task is complete:
156 |
157 | $schedule->command('emails:send')
158 | ->daily()
159 | ->before(function () {
160 | // Task is about to start...
161 | })
162 | ->after(function () {
163 | // Task is complete...
164 | });
165 |
166 | #### Pinging URLs
167 |
168 | Using the `pingBefore` and `thenPing` methods, the scheduler can automatically ping a given URL before or after a task is complete. This method is useful for notifying an external service, such as [Laravel Envoyer](https://envoyer.io), that your scheduled task is commencing or complete:
169 |
170 | $schedule->command('emails:send')
171 | ->daily()
172 | ->pingBefore($url)
173 | ->thenPing($url);
174 |
175 | Using either the `pingBefore($url)` or `thenPing($url)` feature requires the Guzzle HTTP library. You can add Guzzle to your project by adding the following line to your `composer.json` file:
176 |
177 | "guzzlehttp/guzzle": "~5.3|~6.0"
--------------------------------------------------------------------------------
/seeding.md:
--------------------------------------------------------------------------------
1 | # Database: Seeding
2 |
3 | - [Introduction](#introduction)
4 | - [Writing Seeders](#writing-seeders)
5 | - [Using Model Factories](#using-model-factories)
6 | - [Calling Additional Seeders](#calling-additional-seeders)
7 | - [Running Seeders](#running-seeders)
8 |
9 |
10 | ## Introduction
11 |
12 | Laravel includes a simple method of seeding your database with test data using seed classes. All seed classes are stored in `database/seeds`. Seed classes may have any name you wish, but probably should follow some sensible convention, such as `UsersTableSeeder`, 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.
13 |
14 |
15 | ## Writing Seeders
16 |
17 | To generate a seeder, you may issue the `make:seeder` [Artisan command](/{{version}}/artisan). All seeders generated by the framework will be placed in the `database/seeders` directory:
18 |
19 | php artisan make:seeder UsersTableSeeder
20 |
21 | A seeder class only contains one method by default: `run`. This method is called when the `db:seed` [Artisan command](/{{version}}/artisan) is executed. Within the `run` method, you may insert data into your database however you wish. You may use the [query builder](/{{version}}/queries) to manually insert data or you may use [Eloquent model factories](/{{version}}/testing#model-factories).
22 |
23 | As an example, let's modify the `DatabaseSeeder` class which is included with a default installation of Laravel. Let's add a database insert statement to the `run` method:
24 |
25 | insert([
40 | 'name' => str_random(10),
41 | 'email' => str_random(10).'@gmail.com',
42 | 'password' => bcrypt('secret'),
43 | ]);
44 | }
45 | }
46 |
47 |
48 | ### Using Model Factories
49 |
50 | Of course, manually specifying the attributes for each model seed is cumbersome. Instead, you can use [model factories](/{{version}}/testing#model-factories) to conveniently generate large amounts of database records. First, review the [model factory documentation](/{{version}}/testing#model-factories) to learn how to define your factories. Once you have defined your factories, you may use the `factory` helper function to insert records into your database.
51 |
52 | For example, let's create 50 users and attach a relationship to each user:
53 |
54 | /**
55 | * Run the database seeds.
56 | *
57 | * @return void
58 | */
59 | public function run()
60 | {
61 | factory(App\User::class, 50)->create()->each(function($u) {
62 | $u->posts()->save(factory(App\Post::class)->make());
63 | });
64 | }
65 |
66 |
67 | ### Calling Additional Seeders
68 |
69 | Within the `DatabaseSeeder` class, you may use the `call` method to execute additional seed classes. Using the `call` method allows you to break up your database seeding into multiple files so that no single seeder class becomes overwhelmingly large. Simply pass the name of the seeder class you wish to run:
70 |
71 | /**
72 | * Run the database seeds.
73 | *
74 | * @return void
75 | */
76 | public function run()
77 | {
78 | Model::unguard();
79 |
80 | $this->call(UsersTableSeeder::class);
81 | $this->call(PostsTableSeeder::class);
82 | $this->call(CommentsTableSeeder::class);
83 |
84 | Model::reguard();
85 | }
86 |
87 |
88 | ## Running Seeders
89 |
90 | Once you have written your seeder classes, you may use the `db:seed` Artisan command to seed your database. By default, the `db:seed` command runs the `DatabaseSeeder` class, which may be used to call other seed classes. However, you may use the `--class` option to specify a specific seeder class to run individually:
91 |
92 | php artisan db:seed
93 |
94 | php artisan db:seed --class=UserTableSeeder
95 |
96 | You may also seed your database using the `migrate:refresh` command, which will also rollback and re-run all of your migrations. This command is useful for completely re-building your database:
97 |
98 | php artisan migrate:refresh --seed
--------------------------------------------------------------------------------
/session.md:
--------------------------------------------------------------------------------
1 | # Session
2 |
3 | - [Introduction](#introduction)
4 | - [Basic Usage](#basic-usage)
5 | - [Flash Data](#flash-data)
6 | - [Adding Custom Session Drivers](#adding-custom-session-drivers)
7 |
8 |
9 | ## Introduction
10 |
11 | Since HTTP driven applications are stateless, sessions provide a way to store information about the user across requests. Laravel ships with a variety of session back-ends available for use through a clean, unified API. Support for popular back-ends such as [Memcached](http://memcached.org), [Redis](http://redis.io), and databases is included out of the box.
12 |
13 | ### Configuration
14 |
15 | The session configuration file is stored at `config/session.php`. Be sure to review the well documented options available to you in this file. By default, Laravel is configured to use the `file` session driver, which will work well for many applications. In production applications, you may consider using the `memcached` or `redis` drivers for even faster session performance.
16 |
17 | The session `driver` defines where session data will be stored for each request. Laravel ships with several great drivers out of the box:
18 |
19 |
20 | - `file` - sessions are stored in `storage/framework/sessions`.
21 | - `cookie` - sessions are stored in secure, encrypted cookies.
22 | - `database` - sessions are stored in a database used by your application.
23 | - `memcached` / `redis` - sessions are stored in one of these fast, cache based stores.
24 | - `array` - sessions are stored in a simple PHP array and will not be persisted across requests.
25 |
26 |
27 | > **Note:** The array driver is typically used for running [tests](/{{version}}/testing) to prevent session data from persisting.
28 |
29 | ### Driver Prerequisites
30 |
31 | #### Database
32 |
33 | When using the `database` session driver, you will need to setup a table to contain the session items. Below is an example `Schema` declaration for the table:
34 |
35 | Schema::create('sessions', function ($table) {
36 | $table->string('id')->unique();
37 | $table->text('payload');
38 | $table->integer('last_activity');
39 | });
40 |
41 | You may use the `session:table` Artisan command to generate this migration for you!
42 |
43 | php artisan session:table
44 |
45 | composer dump-autoload
46 |
47 | php artisan migrate
48 |
49 | #### Redis
50 |
51 | Before using Redis sessions with Laravel, you will need to install the `predis/predis` package (~1.0) via Composer.
52 |
53 | ### Other Session Considerations
54 |
55 | The Laravel framework uses the `flash` session key internally, so you should not add an item to the session by that name.
56 |
57 | If you need all stored session data to be encrypted, set the `encrypt` configuration option to `true`.
58 |
59 |
60 | ## Basic Usage
61 |
62 | #### Accessing The Session
63 |
64 | First, let's access the session. We can access the session instance via the HTTP request, which can be type-hinted on a controller method. Remember, controller method dependencies are injected via the Laravel [service container](/{{version}}/container):
65 |
66 | session()->get('key');
85 |
86 | //
87 | }
88 | }
89 |
90 | When you retrieve a value from the session, you may also pass a default value as the second argument to the `get` method. This default value will be returned if the specified key does not exist in the session. If you pass a `Closure` as the default value to the `get` method, the `Closure` will be executed and its result returned:
91 |
92 | $value = $request->session()->get('key', 'default');
93 |
94 | $value = $request->session()->get('key', function() {
95 | return 'default';
96 | });
97 |
98 | If you would like to retrieve all data from the session, you may use the `all` method:
99 |
100 | $data = $request->session()->all();
101 |
102 | You may also use the global `session` PHP function to retrieve and store data in the session:
103 |
104 | Route::get('home', function () {
105 | // Retrieve a piece of data from the session...
106 | $value = session('key');
107 |
108 | // Store a piece of data in the session...
109 | session(['key' => 'value']);
110 | });
111 |
112 | #### Determining If An Item Exists In The Session
113 |
114 | The `has` method may be used to check if an item exists in the session. This method will return `true` if the item exists:
115 |
116 | if ($request->session()->has('users')) {
117 | //
118 | }
119 |
120 | #### Storing Data In The Session
121 |
122 | Once you have access to the session instance, you may call a variety of functions to interact with the underlying data. For example, the `put` method stores a new piece of data in the session:
123 |
124 | $request->session()->put('key', 'value');
125 |
126 | #### Pushing To Array Session Values
127 |
128 | The `push` method may be used to push a new value onto a session value that is an array. For example, if the `user.teams` key contains an array of team names, you may push a new value onto the array like so:
129 |
130 | $request->session()->push('user.teams', 'developers');
131 |
132 | #### Retrieving And Deleting An Item
133 |
134 | The `pull` method will retrieve and delete an item from the session:
135 |
136 | $value = $request->session()->pull('key', 'default');
137 |
138 | #### Deleting Items From The Session
139 |
140 | The `forget` method will remove a piece of data from the session. If you would like to remove all data from the session, you may use the `flush` method:
141 |
142 | $request->session()->forget('key');
143 |
144 | $request->session()->flush();
145 |
146 | #### Regenerating The Session ID
147 |
148 | If you need to regenerate the session ID, you may use the `regenerate` method:
149 |
150 | $request->session()->regenerate();
151 |
152 |
153 | ### Flash Data
154 |
155 | Sometimes you may wish to store items in the session only for the next request. You may do so using the `flash` method. Data stored in the session using this method will only be available during the subsequent HTTP request, and then will be deleted. Flash data is primarily useful for short-lived status messages:
156 |
157 | $request->session()->flash('status', 'Task was successful!');
158 |
159 | If you need to keep your flash data around for even more requests, you may use the `reflash` method, which will keep all of the flash data around for an additional request. If you only need to keep specific flash data around, you may use the `keep` method:
160 |
161 | $request->session()->reflash();
162 |
163 | $request->session()->keep(['username', 'email']);
164 |
165 |
166 | ## Adding Custom Session Drivers
167 |
168 | To add additional drivers to Laravel's session back-end, you may use the `extend` method on the `Session` [facade](/{{version}}/facades). You can call the `extend` method from the `boot` method of a [service provider](/{{version}}/providers):
169 |
170 |
223 | - The `open` method would typically be used in file based session store systems. Since Laravel ships with a `file` session driver, you will almost never need to put anything in this method. You can leave it as an empty stub. It is simply a fact of poor interface design (which we'll discuss later) that PHP requires us to implement this method.
224 | - The `close` method, like the `open` method, can also usually be disregarded. For most drivers, it is not needed.
225 | - The `read` method should return the string version of the session data associated with the given `$sessionId`. There is no need to do any serialization or other encoding when retrieving or storing session data in your driver, as Laravel will perform the serialization for you.
226 | - The `write` method should write the given `$data` string associated with the `$sessionId` to some persistent storage system, such as MongoDB, Dynamo, etc.
227 | - The `destroy` method should remove the data associated with the `$sessionId` from persistent storage.
228 | - The `gc` method should destroy all session data that is older than the given `$lifetime`, which is a UNIX timestamp. For self-expiring systems like Memcached and Redis, this method may be left empty.
229 |
230 |
231 | Once the session driver has been registered, you may use the `mongo` driver in your `config/session.php` configuration file.
232 |
--------------------------------------------------------------------------------
/structure.md:
--------------------------------------------------------------------------------
1 | # Application Structure
2 |
3 | - [Introduction](#introduction)
4 | - [The Root Directory](#the-root-directory)
5 | - [The App Directory](#the-app-directory)
6 | - [Namespacing Your Application](#namespacing-your-application)
7 |
8 |
9 | ## Introduction
10 |
11 | The default Laravel application structure is intended to provide a great starting point for both large and small applications. Of course, you are free to organize your application however you like. Laravel imposes almost no restrictions on where any given class is located - as long as Composer can autoload the class.
12 |
13 |
14 | ## The Root Directory
15 |
16 | The root directory of a fresh Laravel installation contains a variety of folders:
17 |
18 | The `app` directory, as you might expect, contains the core code of your application. We'll explore this folder in more detail soon.
19 |
20 | The `bootstrap` folder contains a few files that bootstrap the framework and configure autoloading, as well as a `cache` folder that contains a few framework generated files for bootstrap performance optimization.
21 |
22 | The `config` directory, as the name implies, contains all of your application's configuration files.
23 |
24 | The `database` folder contains your database migration and seeds. If you wish, you may also use this folder to hold an SQLite database.
25 |
26 | The `public` directory contains the front controller and your assets (images, JavaScript, CSS, etc.).
27 |
28 | The `resources` directory contains your views, raw assets (LESS, SASS, CoffeeScript), and localization files.
29 |
30 | The `storage` directory contains compiled Blade templates, file based sessions, file caches, and other files generated by the framework. This folder is segregated into `app`, `framework`, and `logs` directories. The `app` directory may be used to store any files utilized by your application. The `framework` directory is used to store framework generated files and caches. Finally, the `logs` directory contains your application's log files.
31 |
32 | The `tests` directory contains your automated tests. An example [PHPUnit](https://phpunit.de/) is provided out of the box.
33 |
34 | The `vendor` directory contains your [Composer](https://getcomposer.org) dependencies.
35 |
36 |
37 | ## The App Directory
38 |
39 | The "meat" of your application lives in the `app` directory. By default, this directory is namespaced under `App` and is autoloaded by Composer using the [PSR-4 autoloading standard](http://www.php-fig.org/psr/psr-4/). **You may change this namespace using the `app:name` Artisan command**.
40 |
41 | The `app` directory ships with a variety of additional directories such as `Console`, `Http`, and `Providers`. Think of the `Console` and `Http` directories as providing an API into the "core" of your application. The HTTP protocol and CLI are both mechanisms to interact with your application, but do not actually contain application logic. In other words, they are simply two ways of issuing commands to your application. The `Console` directory contains all of your Artisan commands, while the `Http` directory contains your controllers, filters, and requests.
42 |
43 | The `Jobs` directory, of course, houses the [queueable jobs](/{{version}}/queues) for your application. Jobs may be queued by your application, as well as be run synchronously within the current request lifecycle.
44 |
45 | The `Events` directory, as you might expect, houses [event classes](/{{version}}/events). Events may be used to alert other parts of your application that a given action has occurred, providing a great deal of flexibility and decoupling.
46 |
47 | The `Listeners` directory contains the handler classes for your events. Handlers receive an event and perform logic in response to the event being fired. For example, a `UserRegistered` event might be handled by a `SendWelcomeEmail` listener.
48 |
49 | The `Exceptions` directory contains your application's exception handler and is also a good place to stick any exceptions thrown by your application.
50 |
51 | > **Note:** Many of the classes in the `app` directory can be generated by Artisan via commands. To review the available commands, run the `php artisan list make` command in your terminal.
52 |
53 |
54 | ## Namespacing Your Application
55 |
56 | As discussed above, the default application namespace is `App`; however, you may change this namespace to match the name of your application, which is easily done via the `app:name` Artisan command. For example, if your application is named "SocialNet", you would run the following command:
57 |
58 | php artisan app:name SocialNet
59 |
60 | Of course, you are free to simply use the `App` namespace.
61 |
--------------------------------------------------------------------------------
/views.md:
--------------------------------------------------------------------------------
1 | # Views
2 |
3 | - [Basic Usage](#basic-usage)
4 | - [Passing Data To Views](#passing-data-to-views)
5 | - [Sharing Data With All Views](#sharing-data-with-all-views)
6 | - [View Composers](#view-composers)
7 |
8 |
9 | ## Basic Usage
10 |
11 | Views contain the HTML served by your application and separate your controller / application logic from your presentation logic. Views are stored in the `resources/views` directory.
12 |
13 | A simple view might look something like this:
14 |
15 |
16 |
17 |
18 |
19 | Hello,
20 |
21 |
22 |
23 | Since this view is stored at `resources/views/greeting.php`, we may return it using the global `view` helper function like so:
24 |
25 | Route::get('/', function () {
26 | return view('greeting', ['name' => 'James']);
27 | });
28 |
29 | As you can see, the first argument passed to the `view` helper corresponds to the name of the view file in the `resources/views` directory. The second argument passed to helper is an array of data that should be made available to the view. In this case, we are passing the `name` variable, which is displayed in the view by simply executing `echo` on the variable.
30 |
31 | Of course, views may also be nested within sub-directories of the `resources/views` directory. "Dot" notation may be used to reference nested views. For example, if your view is stored at `resources/views/admin/profile.php`, you may reference it like so:
32 |
33 | return view('admin.profile', $data);
34 |
35 | #### Determining If A View Exists
36 |
37 | If you need to determine if a view exists, you may use the `exists` method after calling the `view` helper with no arguments. This method will return `true` if the view exists on disk:
38 |
39 | if (view()->exists('emails.customer')) {
40 | //
41 | }
42 |
43 | When the `view` helper is called without arguments, an instance of `Illuminate\Contracts\View\Factory` is returned, giving you access to any of the factory's methods.
44 |
45 |
46 | ### View Data
47 |
48 |
49 | #### Passing Data To Views
50 |
51 | As you saw in the previous examples, you may easily pass an array of data to views:
52 |
53 | return view('greetings', ['name' => 'Victoria']);
54 |
55 | When passing information in this manner, `$data` should be an array with key/value pairs. Inside your view, you can then access each value using its corresponding key, such as ``. As an alternative to passing a complete array of data to the `view` helper function, you may use the `with` method to add individual pieces of data to the view:
56 |
57 | $view = view('greeting')->with('name', 'Victoria');
58 |
59 |
60 | #### Sharing Data With All Views
61 |
62 | Occasionally, you may need to share a piece of data with all views that are rendered by your application. You may do so using the view factory's `share` method. Typically, you would place calls to `share` within a service provider's `boot` method. You are free to add them to the `AppServiceProvider` or generate a separate service provider to house them:
63 |
64 | share('key', 'value');
78 | }
79 |
80 | /**
81 | * Register the service provider.
82 | *
83 | * @return void
84 | */
85 | public function register()
86 | {
87 | //
88 | }
89 | }
90 |
91 |
92 | ## View Composers
93 |
94 | View composers are callbacks or class methods that are called when a view is rendered. If you have data that you want to be bound to a view each time that view is rendered, a view composer can help you organize that logic into a single location.
95 |
96 | Let's register our view composers within a [service provider](/{{version}}/providers). We'll use the `view` helper to access the underlying `Illuminate\Contracts\View\Factory` contract implementation. Remember, Laravel does not include a default directory for view composers. You are free to organize them however you wish. For example, you could create an `App\Http\ViewComposers` directory:
97 |
98 | composer(
115 | 'profile', 'App\Http\ViewComposers\ProfileComposer'
116 | );
117 |
118 | // Using Closure based composers...
119 | view()->composer('dashboard', function ($view) {
120 |
121 | });
122 | }
123 |
124 | /**
125 | * Register the service provider.
126 | *
127 | * @return void
128 | */
129 | public function register()
130 | {
131 | //
132 | }
133 | }
134 |
135 | Remember, if you create a new service provider to contain your view composer registrations, you will need to add the service provider to the `providers` array in the `config/app.php` configuration file.
136 |
137 | Now that we have registered the composer, the `ProfileComposer@compose` method will be executed each time the `profile` view is being rendered. So, let's define the composer class:
138 |
139 | users = $users;
165 | }
166 |
167 | /**
168 | * Bind data to the view.
169 | *
170 | * @param View $view
171 | * @return void
172 | */
173 | public function compose(View $view)
174 | {
175 | $view->with('count', $this->users->count());
176 | }
177 | }
178 |
179 | Just before the view is rendered, the composer's `compose` method is called with the `Illuminate\Contracts\View\View` instance. You may use the `with` method to bind data to the view.
180 |
181 | > **Note:** All view composers are resolved via the [service container](/{{version}}/container), so you may type-hint any dependencies you need within a composer's constructor.
182 |
183 | #### Attaching A Composer To Multiple Views
184 |
185 | You may attach a view composer to multiple views at once by passing an array of views as the first argument to the `composer` method:
186 |
187 | view()->composer(
188 | ['profile', 'dashboard'],
189 | 'App\Http\ViewComposers\MyViewComposer'
190 | );
191 |
192 | The `composer` method accepts the `*` character as a wildcard, allowing you to attach a composer to all views:
193 |
194 | view()->composer('*', function ($view) {
195 | //
196 | });
197 |
198 | ### View Creators
199 |
200 | View **creators** are very similar to view composers; however, they are fired immediately when the view is instantiated instead of waiting until the view is about to render. To register a view creator, use the `creator` method:
201 |
202 | view()->creator('profile', 'App\Http\ViewCreators\ProfileCreator');
203 |
--------------------------------------------------------------------------------