├── README.md
├── apis.md
├── application-testing.md
├── artisan.md
├── authentication.md
├── authorization.md
├── billing.md
├── blade.md
├── broadcasting.md
├── bus.md
├── cache.md
├── collections.md
├── commands.md
├── configuration.md
├── container.md
├── contracts.md
├── contributing.md
├── contributions.md
├── controllers.md
├── csrf.md
├── database-testing.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
├── extending.md
├── facades.md
├── filesystem.md
├── frontend.md
├── hashing.md
├── helpers.md
├── homestead.md
├── html.md
├── installation.md
├── introduction.md
├── license.md
├── lifecycle.md
├── localization.md
├── mail.md
├── middleware.md
├── migrations.md
├── mocking.md
├── notifications.md
├── packages.md
├── pagination.md
├── passport.md
├── passwords.md
├── providers.md
├── queries.md
├── queues.md
├── redirects.md
├── redis.md
├── releases.md
├── requests.md
├── responses.md
├── routing.md
├── scheduling.md
├── schema.md
├── scout.md
├── seeding.md
├── session.md
├── ssh.md
├── structure.md
├── templates.md
├── testing.md
├── upgrade.md
├── valet.md
├── validation.md
└── views.md
/README.md:
--------------------------------------------------------------------------------
1 | # Laravel Dökümantasyonu
2 |
3 | ## Destek ve Düzenlemeler Hakkında
4 |
5 | Eğer **şuanki stabil sürüm** hakkında bir düzenleme gönderecekseniz, bunu ait olduğu branşa gönderin. Örneğin, eğer Laravel 5.3 için bir düzenleme gönderiyorsanız, bunu `5.3` branşına gönderin. Laravel'in bir dahaki sürümü için yapılacak dökümantasyon düzenlemeleri `master` branşına gönderilmelidir.
6 |
7 | ## Sabit Tanımlamalar
8 | {tip} => {tavsiye}
9 |
--------------------------------------------------------------------------------
/apis.md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/laravel-tr/docs/4099e38aa230f20d15bf34d4b061354579b18eb2/apis.md
--------------------------------------------------------------------------------
/bus.md:
--------------------------------------------------------------------------------
1 | # Command Bus
2 |
3 | - [Introduction](#introduction)
4 | - [Creating Commamnds](#creating-commands)
5 | - [Dispatching Commamnds](#dispatching-commands)
6 | - [Queued Commands](#queued-commands)
7 |
8 |
9 | ## Introduction
10 |
11 | The Laravel command bus provides a convenient method of encapsulating tasks your application needs to perform into simple, easy to understand "commands". To help us understand the purpose of commands, let's pretend we are building an application that allows users to purchase podcasts.
12 |
13 | When a user purchases a podcast, there are a variety of things that need to happen. For example, we may need to charge the user's credit card, add a record to our database that represents the purchase, and send a confirmation e-mail of the purchase. Perhaps we also need to perform some kind of validation as to whether the user is allowed to purchase podcasts.
14 |
15 | We could put all of this logic inside a controller method; however, this has several disadvantages. The first disadvantage is that our controller probably handles several other incoming HTTP actions, and including complicated logic in each controller method will soon bloat our controller and make it harder to read. Secondly, it is difficult to re-use the purchase podcast logic outside of the controller context. Thirdly, it is more difficult to unit-test the command as we must also generate a stub HTTP request and make a full request to the application to test the purchase podcast logic.
16 |
17 | Instead of putting this logic in the controller, we may choose to encapsulte it within a "command" object, such as a `PurchasePodcast` command.
18 |
19 |
20 | ## Creating Commands
21 |
22 | The Artisan CLI can generate new command classes using the `make:command` command:
23 |
24 | php artisan make:command PurchasePodcast
25 |
26 | The newly generated class will be placed in the `app/Commands` directory. By default, the command contains two methods: the constructor and the `handle` method. Of course, the constructor allows you to pass any relevant objects to the command, while the `handle` method executes the command. For example:
27 |
28 | class PurchasePodcast extends Command implements SelfHandling {
29 |
30 | protected $user, $podcast;
31 |
32 | /**
33 | * Create a new command instance.
34 | *
35 | * @return void
36 | */
37 | public function __construct(User $user, Podcast $pocast)
38 | {
39 | $this->user = $user;
40 | $this->podcast = $podcast;
41 | }
42 |
43 | /**
44 | * Execute the command.
45 | *
46 | * @return void
47 | */
48 | public function handle()
49 | {
50 | // Handle the logic to purchase the podcast...
51 |
52 | event(new PodcastWasPurchased($this->user, $this->podcast));
53 | }
54 |
55 | }
56 |
57 | The `handle` method may also type-hint dependencies, and they will be automatically injected by the [IoC container](/docs/master/container). For example:
58 |
59 | /**
60 | * Execute the command.
61 | *
62 | * @return void
63 | */
64 | public function handle(BillingGateway $billing)
65 | {
66 | // Handle the logic to purchase the podcast...
67 | }
68 |
69 |
70 | ## Dispatching Commands
71 |
72 | So, once we have created a command, how do we dispatch it? Of course, we could call the `handle` method directly; however, dispatching the command through the Laravel "command bus" has several advantages which we will discuss later.
73 |
74 | If you glance at your application's base controller, you will see the `DispatchesCommands` trait. This trait allows us to call the `dispatch` method from any of our controllers. For example:
75 |
76 | public function purchasePodcast($podcastId)
77 | {
78 | $this->dispatch(
79 | new PurchasePodcast(Auth::user(), Podcast::findOrFail($podcastId))
80 | );
81 | }
82 |
83 | The command bus will take care of executing the command and calling the IoC container to inject any needed dependencies into the `handle` method.
84 |
85 | You may add the `Illuminate\Foundation\Bus\DispatchesCommands` trait to any class you wish. If you would like to receive a command bus instance through the constructor of any of your classes, you may type-hint the `Illuminate\Contracts\Bus\Dispatcher` interface. Finally, you may also use the `Bus` facade to quickly dispatch commands:
86 |
87 | Bus::dispatch(
88 | new PurchasePodcast(Auth::user(), Podcast::findOrFail($podcastId))
89 | );
90 |
91 | ### Mapping Command Properties From Requests
92 |
93 | It is very common to map HTTP request variables into commands. So, instead of forcing you to do this manually for each request, Laravel provides some helper methods to make it a cinch. Let's take a look at the `dispatchFrom` method available on the `DispatchesCommands` trait:
94 |
95 | $this->dispatchFrom('Command\Class\Name', $request);
96 |
97 | This method will examine the constructor of the command class it is given, and then extract variables from the HTTP request (or any other `ArrayAccess` object) to fill the needed constructor parameters of the command. So, if our command class accepts a `firstName` variable in its constructor, the command bus will attempt to pull the `firstName` parameter from the HTTP request.
98 |
99 | You may also pass an array as the third argument to the `dispatchFrom` method. This array will be used to fill any constructor parameters that are not available on the request:
100 |
101 | $this->dispatchFrom('Command\Class\Name', $request, [
102 | 'firstName' => 'Taylor',
103 | ]);
104 |
105 |
106 | ## Queued Commands
107 |
108 | The command bus is not just for synchronous jobs that run during the current request cycle, but also serves as the primary way to build queued jobs in Laravel. So, how do we instruct command bus to queue our job for background processing instead of running it synchronously? It's easy. Firstly, when generating a new command, just add the `--queued` flag to the command:
109 |
110 | php artisan make:command PurchasePodcast --queued
111 |
112 | As you will see, this adds a few more features to the command, namely the `Illuminate\Contracts\Queue\ShouldBeQueued` interface and the `SerializesModels` trait. These instruct the command bus to queue the command, as well as gracefully serialize and deserialize any Eloquent models your command stores as properties.
113 |
114 | If you would like to convert an existing command into a queued command, simply implement the `Illuminate\Contracts\Queue\ShouldBeQueued` interface on the class manually. It contains no methods, and merely serves as a "marker interface" for the dispatcher.
115 |
116 | Then, just write your command normally. When you dispatch it to the bus that bus will automatically queue the command for background processing. It doesn't get any easier than that.
117 |
118 | For more information on interacting with queued commands, view the full [queue documentation](/docs/master/queues).
119 |
--------------------------------------------------------------------------------
/commands.md:
--------------------------------------------------------------------------------
1 | # Artisan Development
2 |
3 | - [Introduction](#introduction)
4 | - [Building A Command](#building-a-command)
5 | - [Registering Commands](#registering-commands)
6 |
7 |
8 | ## Introduction
9 |
10 | In addition to the commands provided with Artisan, you may also build your own custom commands for working with your application. You may store your custom commands in the `app/Console/Commands` directory; however, you are free to choose your own storage location as long as your commands can be autoloaded based on your `composer.json` settings.
11 |
12 |
13 | ## Building A Command
14 |
15 | ### Generating The Class
16 |
17 | To create a new command, you may use the `make:console` Artisan command, which will generate a command stub to help you get started:
18 |
19 | #### Generate A New Command Class
20 |
21 | php artisan make:console FooCommand
22 |
23 | The command above would generate a class at `app/Console/FooCommand.php`.
24 |
25 | When creating the command, the `--command` option may be used to assign the terminal command name:
26 |
27 | php artisan make:console AssignUsers --command=users:assign
28 |
29 | ### Writing The Command
30 |
31 | Once your command is generated, you should fill out the `name` and `description` properties of the class, which will be used when displaying your command on the `list` screen.
32 |
33 | The `fire` method will be called when your command is executed. You may place any command logic in this method.
34 |
35 | ### Arguments & Options
36 |
37 | The `getArguments` and `getOptions` methods are where you may define any arguments or options your command receives. Both of these methods return an array of commands, which are described by a list of array options.
38 |
39 | When defining `arguments`, the array definition values represent the following:
40 |
41 | array($name, $mode, $description, $defaultValue)
42 |
43 | The argument `mode` may be any of the following: `InputArgument::REQUIRED` or `InputArgument::OPTIONAL`.
44 |
45 | When defining `options`, the array definition values represent the following:
46 |
47 | array($name, $shortcut, $mode, $description, $defaultValue)
48 |
49 | For options, the argument `mode` may be: `InputOption::VALUE_REQUIRED`, `InputOption::VALUE_OPTIONAL`, `InputOption::VALUE_IS_ARRAY`, `InputOption::VALUE_NONE`.
50 |
51 | The `VALUE_IS_ARRAY` mode indicates that the switch may be used multiple times when calling the command:
52 |
53 | php artisan foo --option=bar --option=baz
54 |
55 | The `VALUE_NONE` option indicates that the option is simply used as a "switch":
56 |
57 | php artisan foo --option
58 |
59 | ### Retrieving Input
60 |
61 | While your command is executing, you will obviously need to access the values for the arguments and options accepted by your application. To do so, you may use the `argument` and `option` methods:
62 |
63 | #### Retrieving The Value Of A Command Argument
64 |
65 | $value = $this->argument('name');
66 |
67 | #### Retrieving All Arguments
68 |
69 | $arguments = $this->argument();
70 |
71 | #### Retrieving The Value Of A Command Option
72 |
73 | $value = $this->option('name');
74 |
75 | #### Retrieving All Options
76 |
77 | $options = $this->option();
78 |
79 | ### Writing Output
80 |
81 | To send output to the console, you may use the `info`, `comment`, `question` and `error` methods. Each of these methods will use the appropriate ANSI colors for their purpose.
82 |
83 | #### Sending Information To The Console
84 |
85 | $this->info('Display this on the screen');
86 |
87 | #### Sending An Error Message To The Console
88 |
89 | $this->error('Something went wrong!');
90 |
91 | ### Asking Questions
92 |
93 | You may also use the `ask` and `confirm` methods to prompt the user for input:
94 |
95 | #### Asking The User For Input
96 |
97 | $name = $this->ask('What is your name?');
98 |
99 | #### Asking The User For Secret Input
100 |
101 | $password = $this->secret('What is the password?');
102 |
103 | #### Asking The User For Confirmation
104 |
105 | if ($this->confirm('Do you wish to continue? [yes|no]'))
106 | {
107 | //
108 | }
109 |
110 | You may also specify a default value to the `confirm` method, which should be `true` or `false`:
111 |
112 | $this->confirm($question, true);
113 |
114 | ### Calling Other Commands
115 |
116 | Sometimes you may wish to call other commands from your command. You may do so using the `call` method:
117 |
118 | $this->call('command:name', ['argument' => 'foo', '--option' => 'bar']);
119 |
120 |
121 | ## Registering Commands
122 |
123 | #### Registering An Artisan Command
124 |
125 | Once your command is finished, you need to register it with Artisan so it will be available for use. This is typically done in the `app/Console/Kernel.php` file. Within this file, you will find a list of commands in the `commands` property. To register your command, simply add it to this list. When Artisan boots, all the commands listed in this property will be resolved by the [IoC container](/docs/master/container) and registered with Artisan.
126 |
--------------------------------------------------------------------------------
/configuration.md:
--------------------------------------------------------------------------------
1 | # Configuration
2 |
3 | - [Introduction](#introduction)
4 | - [Accessing Configuration Values](#accessing-configuration-values)
5 | - [Environment Configuration](#environment-configuration)
6 | - [Determining The Current Environment](#determining-the-current-environment)
7 | - [Configuration Caching](#configuration-caching)
8 | - [Maintenance Mode](#maintenance-mode)
9 |
10 |
11 | ## Introduction
12 |
13 | All of the configuration files for the Laravel framework are stored in the `config` directory. Each option is documented, so feel free to look through the files and get familiar with the options available to you.
14 |
15 |
16 | ## Accessing Configuration Values
17 |
18 | You may easily access your configuration values using the global `config` helper function from anywhere in your application. The configuration values may be accessed using "dot" syntax, which includes the name of the file and option you wish to access. A default value may also be specified and will be returned if the configuration option does not exist:
19 |
20 | $value = config('app.timezone');
21 |
22 | To set configuration values at runtime, pass an array to the `config` helper:
23 |
24 | config(['app.timezone' => 'America/Chicago']);
25 |
26 |
27 | ## Environment Configuration
28 |
29 | It is often helpful to have different configuration values based on the environment the application is running in. For example, you may wish to use a different cache driver locally than you do on your production server.
30 |
31 | To make this a cinch, Laravel utilizes the [DotEnv](https://github.com/vlucas/phpdotenv) PHP library by Vance Lucas. In a fresh Laravel installation, the root directory of your application will contain a `.env.example` file. If you install Laravel via Composer, this file will automatically be renamed to `.env`. Otherwise, you should rename the file manually.
32 |
33 | #### Retrieving Environment Configuration
34 |
35 | All of the variables listed in this file will be loaded into the `$_ENV` PHP super-global when your application receives a request. However, you may use the `env` helper to retrieve values from these variables in your configuration files. In fact, if you review the Laravel configuration files, you will notice several of the options already using this helper:
36 |
37 | 'debug' => env('APP_DEBUG', false),
38 |
39 | The second value passed to the `env` function is the "default value". This value will be used if no environment variable exists for the given key.
40 |
41 | Your `.env` file should not be committed to your application's source control, since each developer / server using your application could require a different environment configuration.
42 |
43 | If you are developing with a team, you may wish to continue including a `.env.example` file with your application. By putting place-holder values in the example configuration file, other developers on your team can clearly see which environment variables are needed to run your application.
44 |
45 |
46 | ### Determining The Current Environment
47 |
48 | The current application environment is determined via the `APP_ENV` variable from your `.env` file. You may access this value via the `environment` method on the `App` [facade](/docs/{{version}}/facades):
49 |
50 | $environment = App::environment();
51 |
52 | You may also pass arguments to the `environment` method to check if the environment matches a given value. The method will return `true` if the environment matches any of the given values:
53 |
54 | if (App::environment('local')) {
55 | // The environment is local
56 | }
57 |
58 | if (App::environment('local', 'staging')) {
59 | // The environment is either local OR staging...
60 | }
61 |
62 |
63 | ## Configuration Caching
64 |
65 | To give your application a speed boost, you should cache all of your configuration files into a single file using the `config:cache` Artisan command. This will combine all of the configuration options for your application into a single file which will be loaded quickly by the framework.
66 |
67 | You should typically run the `php artisan config:cache` command as part of your production deployment routine. The command should not be run during local development as configuration options will frequently need to be changed during the course of your application's development.
68 |
69 |
70 | ## Maintenance Mode
71 |
72 | When your application is in maintenance mode, a custom view will be displayed for all requests into your application. This makes it easy to "disable" your application while it is updating or when you are performing maintenance. A maintenance mode check is included in the default middleware stack for your application. If the application is in maintenance mode, a `MaintenanceModeException` will be thrown with a status code of 503.
73 |
74 | To enable maintenance mode, simply execute the `down` Artisan command:
75 |
76 | php artisan down
77 |
78 | You may also provide `message` and `retry` options to the `down` command. The `message` value may be used to display or log a custom message, while the `retry` value will be set as the `Retry-After` HTTP header's value:
79 |
80 | php artisan down --message='Upgrading Database' --retry=60
81 |
82 | To disable maintenance mode, use the `up` command:
83 |
84 | php artisan up
85 |
86 | #### Maintenance Mode Response Template
87 |
88 | The default template for maintenance mode responses is located in `resources/views/errors/503.blade.php`. You are free to modify this view as needed for your application.
89 |
90 | #### Maintenance Mode & Queues
91 |
92 | While your application is in maintenance mode, no [queued jobs](/docs/{{version}}/queues) will be handled. The jobs will continue to be handled as normal once the application is out of maintenance mode.
93 |
94 | #### Alternatives To Maintenance Mode
95 |
96 | Since maintenance mode requires your application to have several seconds of downtime, consider alternatives like [Envoyer](https://envoyer.io) to accomplish zero-downtime deployment with Laravel.
97 |
--------------------------------------------------------------------------------
/contributing.md:
--------------------------------------------------------------------------------
1 | # Contribution Guidelines
2 |
3 | If you are submitting documentation for the **current stable release**, submit it to the corresponding branch. For example, documentation for Laravel 5.1 would be submitted to the `5.1` branch. Documentation intended for the next release of Laravel should be submitted to the `master` branch.
--------------------------------------------------------------------------------
/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 | - [PHPDoc](#phpdoc)
9 | - [StyleCI](#styleci)
10 |
11 |
12 | ## Bug Reports
13 |
14 | 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.
15 |
16 | 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.
17 |
18 | 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.
19 |
20 | The Laravel source code is managed on Github, and there are repositories for each of the Laravel projects:
21 |
22 | - [Laravel Framework](https://github.com/laravel/framework)
23 | - [Laravel Application](https://github.com/laravel/laravel)
24 | - [Laravel Documentation](https://github.com/laravel/docs)
25 | - [Laravel Cashier](https://github.com/laravel/cashier)
26 | - [Laravel Cashier for Braintree](https://github.com/laravel/cashier-braintree)
27 | - [Laravel Envoy](https://github.com/laravel/envoy)
28 | - [Laravel Homestead](https://github.com/laravel/homestead)
29 | - [Laravel Homestead Build Scripts](https://github.com/laravel/settler)
30 | - [Laravel Website](https://github.com/laravel/laravel.com)
31 | - [Laravel Art](https://github.com/laravel/art)
32 |
33 |
34 | ## Core Development Discussion
35 |
36 | You may propose new features or improvements of existing Laravel behavior in the Laravel Internals [issue board](https://github.com/laravel/internals/issues). If you propose a new feature, please be willing to implement at least some of the code that would be needed to complete the feature.
37 |
38 | Informal 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.
39 |
40 |
41 | ## Which Branch?
42 |
43 | **All** bug fixes should be sent to the latest stable branch or to the current LTS branch (5.1). Bug fixes should **never** be sent to the `master` branch unless they fix features that exist only in the upcoming release.
44 |
45 | **Minor** features that are **fully backwards compatible** with the current Laravel release may be sent to the latest stable branch.
46 |
47 | **Major** new features should always be sent to the `master` branch, which contains the upcoming Laravel release.
48 |
49 | 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.
50 |
51 |
52 | ## Security Vulnerabilities
53 |
54 | If you discover a security vulnerability within Laravel, please send an email to Taylor Otwell at taylor@laravel.com. All security vulnerabilities will be promptly addressed.
55 |
56 |
57 | ## Coding Style
58 |
59 | 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.
60 |
61 |
62 | ### PHPDoc
63 |
64 | Below is an example of a valid Laravel documentation block. Note that the `@param` attribute is followed by two spaces, the argument type, two more spaces, and finally the variable name:
65 |
66 | /**
67 | * Register a binding with the container.
68 | *
69 | * @param string|array $abstract
70 | * @param \Closure|string|null $concrete
71 | * @param bool $shared
72 | * @return void
73 | */
74 | public function bind($abstract, $concrete = null, $shared = false)
75 | {
76 | //
77 | }
78 |
79 |
80 | ### StyleCI
81 |
82 | Don't worry if your code styling isn't perfect! [StyleCI](https://styleci.io/) will automatically merge any style fixes into the Laravel repository after pull requests are merged. This allows us to focus on the content of the contribution and not the code style.
83 |
--------------------------------------------------------------------------------
/csrf.md:
--------------------------------------------------------------------------------
1 | # CSRF Protection
2 |
3 | - [Introduction](#csrf-introduction)
4 | - [Excluding URIs](#csrf-excluding-uris)
5 | - [X-CSRF-Token](#csrf-x-csrf-token)
6 | - [X-XSRF-Token](#csrf-x-xsrf-token)
7 |
8 |
9 | ## Introduction
10 |
11 | Laravel makes it easy to protect your application from [cross-site request forgery](http://en.wikipedia.org/wiki/Cross-site_request_forgery) (CSRF) attacks. Cross-site request forgeries are a type of malicious exploit whereby unauthorized commands are performed on behalf of an authenticated user.
12 |
13 | Laravel automatically generates a CSRF "token" for each active user session managed by the application. This token is used to verify that the authenticated user is the one actually making the requests to the application.
14 |
15 | Anytime you define a HTML form in your application, you should include a hidden CSRF token field in the form so that the CSRF protection middleware can validate the request. You may use the `csrf_field` helper to generate the token field:
16 |
17 |
21 |
22 | The `VerifyCsrfToken` [middleware](/docs/{{version}}/middleware), which is included in the `web` middleware group, will automatically verify that the token in the request input matches the token stored in the session.
23 |
24 |
25 | ## Excluding URIs From CSRF Protection
26 |
27 | Sometimes you may wish to exclude a set of URIs from CSRF protection. For example, if you are using [Stripe](https://stripe.com) to process payments and are utilizing their webhook system, you will need to exclude your Stripe webhook handler route from CSRF protection since Stripe will not know what CSRF token to send to your routes.
28 |
29 | Typically, you should place these kinds of routes outside of the `web` middleware group that the `RouteServiceProvider` applies to all routes in the `routes/web.php` file. However, you may also exclude the routes by adding their URIs to the `$except` property of the `VerifyCsrfToken` middleware:
30 |
31 |
50 | ## X-CSRF-TOKEN
51 |
52 | In addition to checking for the CSRF token as a POST parameter, the `VerifyCsrfToken` middleware will also check for the `X-CSRF-TOKEN` request header. You could, for example, store the token in a HTML `meta` tag:
53 |
54 |
55 |
56 | Then, once you have created the `meta` tag, you can instruct a library like jQuery to automatically add the token to all request headers. This provides simple, convenient CSRF protection for your AJAX based applications:
57 |
58 | $.ajaxSetup({
59 | headers: {
60 | 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
61 | }
62 | });
63 |
64 |
65 | ## X-XSRF-TOKEN
66 |
67 | Laravel stores the current CSRF token in a `XSRF-TOKEN` cookie that is included with each response generated by the framework. You can use the cookie value to set the `X-XSRF-TOKEN` request header.
68 |
69 | This cookie is primarily sent as a convenience since some JavaScript frameworks, like Angular, automatically place its value in the `X-XSRF-TOKEN` header.
70 |
--------------------------------------------------------------------------------
/database-testing.md:
--------------------------------------------------------------------------------
1 | # Database Testing
2 |
3 | - [Introduction](#introduction)
4 | - [Resetting The Database After Each Test](#resetting-the-database-after-each-test)
5 | - [Using Migrations](#using-migrations)
6 | - [Using Transactions](#using-transactions)
7 | - [Writing Factories](#writing-factories)
8 | - [Factory States](#factory-states)
9 | - [Using Factories](#using-factories)
10 | - [Creating Models](#creating-models)
11 | - [Persisting Models](#persisting-models)
12 | - [Relationships](#relationships)
13 |
14 |
15 | ## Introduction
16 |
17 | Laravel provides a variety of helpful tools to make it easier to test your database driven applications. First, you may use the `seeInDatabase` helper to assert that data exists in the database matching a given set of criteria. For example, if you would like to verify that there is a record in the `users` table with the `email` value of `sally@example.com`, you can do the following:
18 |
19 | public function testDatabase()
20 | {
21 | // Make call to application...
22 |
23 | $this->seeInDatabase('users', [
24 | 'email' => 'sally@example.com'
25 | ]);
26 | }
27 |
28 | Of course, the `seeInDatabase` method and other helpers like it are for convenience. You are free to use any of PHPUnit's built-in assertion methods to supplement your tests.
29 |
30 |
31 | ## Resetting The Database After Each Test
32 |
33 | It is often useful to reset your database after each test so that data from a previous test does not interfere with subsequent tests.
34 |
35 |
36 | ### Using Migrations
37 |
38 | One approach to resetting the database state is to rollback the database after each test and migrate it before the next test. Laravel provides a simple `DatabaseMigrations` trait that will automatically handle this for you. Simply use the trait on your test class and everything will be handled for you:
39 |
40 | visit('/')
58 | ->see('Laravel 5');
59 | }
60 | }
61 |
62 |
63 | ### Using Transactions
64 |
65 | Another approach to resetting the database state is to wrap each test case in a database transaction. Again, Laravel provides a convenient `DatabaseTransactions` trait that will automatically handle this for you:
66 |
67 | visit('/')
85 | ->see('Laravel 5');
86 | }
87 | }
88 |
89 | > {note} This trait will only wrap the default database connection in a transaction. If your application is using multiple database connections, you will need to manually handle the transaction logic for those connections.
90 |
91 |
92 | ## Writing Factories
93 |
94 | When testing, it is common to need to insert a few records into your database before executing your test. Instead of manually specifying the value of each column when you create this test data, Laravel allows you to define a default set of attributes for each of your [Eloquent models](/docs/{{version}}/eloquent) using model factories. To get started, take a look at the `database/factories/ModelFactory.php` file in your application. Out of the box, this file contains one factory definition:
95 |
96 | $factory->define(App\User::class, function (Faker\Generator $faker) {
97 | return [
98 | 'name' => $faker->name,
99 | 'email' => $faker->email,
100 | 'password' => bcrypt(str_random(10)),
101 | 'remember_token' => str_random(10),
102 | ];
103 | });
104 |
105 | Within the Closure, which serves as the factory definition, you may return the default test values of all attributes on the model. The Closure will receive an instance of the [Faker](https://github.com/fzaninotto/Faker) PHP library, which allows you to conveniently generate various kinds of random data for testing.
106 |
107 | Of course, you are free to add your own additional factories to the `ModelFactory.php` file. You may also create additional factory files for each model for better organization. For example, you could create `UserFactory.php` and `CommentFactory.php` files within your `database/factories` directory. All of the files within the `factories` directory will automatically be loaded by Laravel.
108 |
109 |
110 | ### Factory States
111 |
112 | States allow you to define discrete modifications that can be applied to your model factories in any combination. For example, your `User` model might have a `delinquent` state that modifies one of its default attribute values. You may define your state transformations using the `state` method:
113 |
114 | $factory->state(App\User::class, 'delinquent', function ($faker) {
115 | return [
116 | 'account_status' => 'delinquent',
117 | ];
118 | });
119 |
120 |
121 | ## Using Factories
122 |
123 |
124 | ### Creating Models
125 |
126 | Once you have defined your factories, you may use the global `factory` function in your tests or seed files to generate model instances. So, let's take a look at a few examples of creating models. First, we'll use the `make` method to create models but not save them to the database:
127 |
128 | public function testDatabase()
129 | {
130 | $user = factory(App\User::class)->make();
131 |
132 | // Use model in tests...
133 | }
134 |
135 | You may also create a Collection of many models or create models of a given type:
136 |
137 | // Create three App\User instances...
138 | $users = factory(App\User::class, 3)->make();
139 |
140 | // Create an "admin" App\User instance...
141 | $user = factory(App\User::class, 'admin')->make();
142 |
143 | // Create three "admin" App\User instances...
144 | $users = factory(App\User::class, 'admin', 3)->make();
145 |
146 | #### Applying States
147 |
148 | You may also apply any of your [states](#factory-states) to the models. If you would like to apply multiple state transformations to the models, you should specify the name of each state you would like to apply:
149 |
150 | $users = factory(App\User::class, 5)->states('deliquent')->make();
151 |
152 | $users = factory(App\User::class, 5)->states('premium', 'deliquent')->make();
153 |
154 | #### Overriding Attributes
155 |
156 | If you would like to override some of the default values of your models, you may pass an array of values to the `make` method. Only the specified values will be replaced while the rest of the values remain set to their default values as specified by the factory:
157 |
158 | $user = factory(App\User::class)->make([
159 | 'name' => 'Abigail',
160 | ]);
161 |
162 |
163 | ### Persisting Models
164 |
165 | The `create` method not only creates the model instances but also saves them to the database using Eloquent's `save` method:
166 |
167 | public function testDatabase()
168 | {
169 | // Create a single App\User instance...
170 | $user = factory(App\User::class)->create();
171 |
172 | // Create three App\User instances...
173 | $users = factory(App\User::class, 3)->create();
174 |
175 | // Use model in tests...
176 | }
177 |
178 | You may override attributes on the model by passing an array to the `create` method:
179 |
180 | $user = factory(App\User::class)->create([
181 | 'name' => 'Abigail',
182 | ]);
183 |
184 |
185 | ### Relationships
186 |
187 | In this example, we'll attach a relation to some created models. When using the `create` method to create multiple models, an Eloquent [collection instance](/docs/{{version}}/eloquent-collections) is returned, allowing you to use any of the convenient functions provided by the collection, such as `each`:
188 |
189 | $users = factory(App\User::class, 3)
190 | ->create()
191 | ->each(function ($u) {
192 | $u->posts()->save(factory(App\Post::class)->make());
193 | });
194 |
195 | #### Relations & Attribute Closures
196 |
197 | You may also attach relationships to models using Closure attributes in your factory definitions. For example, if you would like to create a new `User` instance when creating a `Post`, you may do the following:
198 |
199 | $factory->define(App\Post::class, function ($faker) {
200 | return [
201 | 'title' => $faker->title,
202 | 'content' => $faker->paragraph,
203 | 'user_id' => function () {
204 | return factory(App\User::class)->create()->id;
205 | }
206 | ];
207 | });
208 |
209 | These Closures also receive the evaluated attribute array of the factory that contains them:
210 |
211 | $factory->define(App\Post::class, function ($faker) {
212 | return [
213 | 'title' => $faker->title,
214 | 'content' => $faker->paragraph,
215 | 'user_id' => function () {
216 | return factory(App\User::class)->create()->id;
217 | },
218 | 'user_type' => function (array $post) {
219 | return App\User::find($post['user_id'])->type;
220 | }
221 | ];
222 | });
223 |
--------------------------------------------------------------------------------
/database.md:
--------------------------------------------------------------------------------
1 | # Database: Getting Started
2 |
3 | - [Introduction](#introduction)
4 | - [Configuration](#configuration)
5 | - [Read & Write Connections](#read-and-write-connections)
6 | - [Using Multiple Database Connections](#using-multiple-database-connections)
7 | - [Running Raw SQL Queries](#running-queries)
8 | - [Listening For Query Events](#listening-for-query-events)
9 | - [Database Transactions](#database-transactions)
10 |
11 |
12 | ## Introduction
13 |
14 | Laravel makes interacting with databases extremely simple across a variety of database backends using either raw SQL, the [fluent query builder](/docs/{{version}}/queries), and the [Eloquent ORM](/docs/{{version}}/eloquent). Currently, Laravel supports four databases:
15 |
16 |
17 | - MySQL
18 | - Postgres
19 | - SQLite
20 | - SQL Server
21 |
22 |
23 |
24 | ### Configuration
25 |
26 | 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 most of the supported database systems are provided in this file.
27 |
28 | By default, Laravel's sample [environment configuration](/docs/{{version}}/installation#environment-configuration) is ready to use with [Laravel Homestead](/docs/{{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.
29 |
30 | #### SQLite Configuration
31 |
32 | After creating a new SQLite database using a command such as `touch database/database.sqlite`, you can easily configure your environment variables to point to this newly created database by using the database's absolute path:
33 |
34 | DB_CONNECTION=sqlite
35 | DB_DATABASE=/absolute/path/to/database.sqlite
36 |
37 | #### SQL Server Configuration
38 |
39 | Laravel supports SQL Server out of the box; however, you will need to add the connection configuration for the database to your `config/database.php` configuration file:
40 |
41 | 'sqlsrv' => [
42 | 'driver' => 'sqlsrv',
43 | 'host' => env('DB_HOST', 'localhost'),
44 | 'database' => env('DB_DATABASE', 'forge'),
45 | 'username' => env('DB_USERNAME', 'forge'),
46 | 'password' => env('DB_PASSWORD', ''),
47 | 'charset' => 'utf8',
48 | 'prefix' => '',
49 | ],
50 |
51 |
52 | ### Read & Write Connections
53 |
54 | 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.
55 |
56 | To see how read / write connections should be configured, let's look at this example:
57 |
58 | 'mysql' => [
59 | 'read' => [
60 | 'host' => '192.168.1.1',
61 | ],
62 | 'write' => [
63 | 'host' => '196.168.1.2'
64 | ],
65 | 'driver' => 'mysql',
66 | 'database' => 'database',
67 | 'username' => 'root',
68 | 'password' => '',
69 | 'charset' => 'utf8',
70 | 'collation' => 'utf8_unicode_ci',
71 | 'prefix' => '',
72 | ],
73 |
74 | 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.
75 |
76 | You only need to place items in the `read` and `write` arrays if you wish to override the values from the main array. So, in this case, `192.168.1.1` will be used as the host for the "read" connection, while `192.168.1.2` will be used for the "write" connection. The database credentials, prefix, character set, and all other options in the main `mysql` array will be shared across both connections.
77 |
78 |
79 | ### Using Multiple Database Connections
80 |
81 | 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:
82 |
83 | $users = DB::connection('foo')->select(...);
84 |
85 | You may also access the raw, underlying PDO instance using the `getPdo` method on a connection instance:
86 |
87 | $pdo = DB::connection()->getPdo();
88 |
89 |
90 | ## Running Raw SQL Queries
91 |
92 | 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`.
93 |
94 | #### Running A Select Query
95 |
96 | To run a basic query, you may use the `select` method on the `DB` facade:
97 |
98 | $users]);
117 | }
118 | }
119 |
120 | 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.
121 |
122 | 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:
123 |
124 | foreach ($users as $user) {
125 | echo $user->name;
126 | }
127 |
128 | #### Using Named Bindings
129 |
130 | Instead of using `?` to represent your parameter bindings, you may execute a query using named bindings:
131 |
132 | $results = DB::select('select * from users where id = :id', ['id' => 1]);
133 |
134 | #### Running An Insert Statement
135 |
136 | 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 its second argument:
137 |
138 | DB::insert('insert into users (id, name) values (?, ?)', [1, 'Dayle']);
139 |
140 | #### Running An Update Statement
141 |
142 | The `update` method should be used to update existing records in the database. The number of rows affected by the statement will be returned:
143 |
144 | $affected = DB::update('update users set votes = 100 where name = ?', ['John']);
145 |
146 | #### Running A Delete Statement
147 |
148 | The `delete` method should be used to delete records from the database. Like `update`, the number of rows affected will be returned:
149 |
150 | $deleted = DB::delete('delete from users');
151 |
152 | #### Running A General Statement
153 |
154 | Some database statements do not return any value. For these types of operations, you may use the `statement` method on the `DB` facade:
155 |
156 | DB::statement('drop table users');
157 |
158 |
159 | ### Listening For Query Events
160 |
161 | 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](/docs/{{version}}/providers):
162 |
163 | sql
181 | // $query->bindings
182 | // $query->time
183 | });
184 | }
185 |
186 | /**
187 | * Register the service provider.
188 | *
189 | * @return void
190 | */
191 | public function register()
192 | {
193 | //
194 | }
195 | }
196 |
197 |
198 | ## Database Transactions
199 |
200 | You may use the `transaction` method on the `DB` facade to run a set of operations within a database transaction. 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:
201 |
202 | DB::transaction(function () {
203 | DB::table('users')->update(['votes' => 1]);
204 |
205 | DB::table('posts')->delete();
206 | });
207 |
208 | #### Manually Using Transactions
209 |
210 | 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:
211 |
212 | DB::beginTransaction();
213 |
214 | You can rollback the transaction via the `rollBack` method:
215 |
216 | DB::rollBack();
217 |
218 | Lastly, you can commit a transaction via the `commit` method:
219 |
220 | DB::commit();
221 |
222 | > {tip} Using the `DB` facade's transaction methods also controls transactions for the [query builder](/docs/{{version}}/queries) and [Eloquent ORM](/docs/{{version}}/eloquent).
223 |
--------------------------------------------------------------------------------
/documentation.md:
--------------------------------------------------------------------------------
1 | - Prologue
2 | - [Release Notes](/docs/{{version}}/releases)
3 | - [Upgrade Guide](/docs/{{version}}/upgrade)
4 | - [Contribution Guide](/docs/{{version}}/contributions)
5 | - [API Documentation](/api/{{version}})
6 | - Getting Started
7 | - [Installation](/docs/{{version}}/installation)
8 | - [Configuration](/docs/{{version}}/configuration)
9 | - [Directory Structure](/docs/{{version}}/structure)
10 | - [Errors & Logging](/docs/{{version}}/errors)
11 | - Dev Environments
12 | - [Homestead](/docs/{{version}}/homestead)
13 | - [Valet](/docs/{{version}}/valet)
14 | - Core Concepts
15 | - [Service Container](/docs/{{version}}/container)
16 | - [Service Providers](/docs/{{version}}/providers)
17 | - [Facades](/docs/{{version}}/facades)
18 | - [Contracts](/docs/{{version}}/contracts)
19 | - The HTTP Layer
20 | - [Routing](/docs/{{version}}/routing)
21 | - [Middleware](/docs/{{version}}/middleware)
22 | - [CSRF Protection](/docs/{{version}}/csrf)
23 | - [Controllers](/docs/{{version}}/controllers)
24 | - [Requests](/docs/{{version}}/requests)
25 | - [Responses](/docs/{{version}}/responses)
26 | - [Session](/docs/{{version}}/session)
27 | - [Validation](/docs/{{version}}/validation)
28 | - Views & Templates
29 | - [Views](/docs/{{version}}/views)
30 | - [Blade Templates](/docs/{{version}}/blade)
31 | - [Localization](/docs/{{version}}/localization)
32 | - JavaScript & CSS
33 | - [Getting Started](/docs/{{version}}/frontend)
34 | - [Compiling Assets](/docs/{{version}}/elixir)
35 | - Security
36 | - [Authentication](/docs/{{version}}/authentication)
37 | - [Authorization](/docs/{{version}}/authorization)
38 | - [Password Reset](/docs/{{version}}/passwords)
39 | - [API Authentication](/docs/{{version}}/passport)
40 | - [Encryption](/docs/{{version}}/encryption)
41 | - [Hashing](/docs/{{version}}/hashing)
42 | - General Topics
43 | - [Broadcasting](/docs/{{version}}/broadcasting)
44 | - [Cache](/docs/{{version}}/cache)
45 | - [Events](/docs/{{version}}/events)
46 | - [File Storage](/docs/{{version}}/filesystem)
47 | - [Mail](/docs/{{version}}/mail)
48 | - [Notifications](/docs/{{version}}/notifications)
49 | - [Queues](/docs/{{version}}/queues)
50 | - Database
51 | - [Getting Started](/docs/{{version}}/database)
52 | - [Query Builder](/docs/{{version}}/queries)
53 | - [Pagination](/docs/{{version}}/pagination)
54 | - [Migrations](/docs/{{version}}/migrations)
55 | - [Seeding](/docs/{{version}}/seeding)
56 | - [Redis](/docs/{{version}}/redis)
57 | - Eloquent ORM
58 | - [Getting Started](/docs/{{version}}/eloquent)
59 | - [Relationships](/docs/{{version}}/eloquent-relationships)
60 | - [Collections](/docs/{{version}}/eloquent-collections)
61 | - [Mutators](/docs/{{version}}/eloquent-mutators)
62 | - [Serialization](/docs/{{version}}/eloquent-serialization)
63 | - Artisan Console
64 | - [Commands](/docs/{{version}}/artisan)
65 | - [Task Scheduling](/docs/{{version}}/scheduling)
66 | - Testing
67 | - [Getting Started](/docs/{{version}}/testing)
68 | - [Application Testing](/docs/{{version}}/application-testing)
69 | - [Database](/docs/{{version}}/database-testing)
70 | - [Mocking](/docs/{{version}}/mocking)
71 | - Official Packages
72 | - [Cashier](/docs/{{version}}/billing)
73 | - [Envoy](/docs/{{version}}/envoy)
74 | - [Passport](/docs/{{version}}/passport)
75 | - [Scout](/docs/{{version}}/scout)
76 | - [Socialite](https://github.com/laravel/socialite)
77 | - Appendix
78 | - [Collections](/docs/{{version}}/collections)
79 | - [Helpers](/docs/{{version}}/helpers)
80 | - [Packages](/docs/{{version}}/packages)
81 |
--------------------------------------------------------------------------------
/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 instances 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](/docs/{{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 that may be chained 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 | > {note} While most Eloquent collection methods return a new instance of an Eloquent collection, the `pluck`, `keys`, `zip`, `collapse`, `flatten` and `flip` methods return a [base collection](/docs/{{version}}/collections) instance. Likewise, if a `map` operation returns a collection that does not contain any Eloquent models, it will be automatically cast to a base collection.
32 |
33 |
34 | ## Available Methods
35 |
36 | ### The Base Collection
37 |
38 | All Eloquent collections extend the base [Laravel collection](/docs/{{version}}/collections) object; therefore, they inherit all of the powerful methods provided by the base collection class:
39 |
40 |
50 |
51 |
119 |
120 |
121 | ## Custom Collections
122 |
123 | If you need to use a custom `Collection` object with your own extension methods, you may override the `newCollection` method on your model:
124 |
125 |
12 | ## Introduction
13 |
14 | Accessors and mutators allow you to format Eloquent attribute values when you retrieve or set them on model instances. For example, you may want to use the [Laravel encrypter](/docs/{{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.
15 |
16 | 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).
17 |
18 |
19 | ## Accessors & Mutators
20 |
21 |
22 | ### Defining An Accessor
23 |
24 | To define an accessor, create a `getFooAttribute` method on your model where `Foo` is the "studly" 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 the `first_name` attribute:
25 |
26 | first_name;
51 |
52 |
53 | ### Defining A Mutator
54 |
55 | To define a mutator, define a `setFooAttribute` method on your model where `Foo` is the "studly" 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:
56 |
57 | attributes['first_name'] = strtolower($value);
74 | }
75 | }
76 |
77 | 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`:
78 |
79 | $user = App\User::find(1);
80 |
81 | $user->first_name = 'Sally';
82 |
83 | 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 resulting value in the internal `$attributes` array.
84 |
85 |
86 | ## Date Mutators
87 |
88 | By default, Eloquent will convert the `created_at` and `updated_at` columns to instances of [Carbon](https://github.com/briannesbitt/Carbon), which extends the PHP `DateTime` class to provide an assortment of helpful methods. You may customize which dates are automatically mutated, and even completely disable this mutation, by overriding the `$dates` property of your model:
89 |
90 | deleted_at = Carbon::now();
115 |
116 | $user->save();
117 |
118 | 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:
119 |
120 | $user = App\User::find(1);
121 |
122 | return $user->deleted_at->getTimestamp();
123 |
124 | #### Date Formats
125 |
126 | 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:
127 |
128 |
145 | ## Attribute Casting
146 |
147 | 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 and the value is the type you wish to cast the column to. The supported cast types are: `integer`, `real`, `float`, `double`, `string`, `boolean`, `object`, `array`, `collection`, `date`, `datetime`, and `timestamp`.
148 |
149 | 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:
150 |
151 | 'boolean',
166 | ];
167 | }
168 |
169 | 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:
170 |
171 | $user = App\User::find(1);
172 |
173 | if ($user->is_admin) {
174 | //
175 | }
176 |
177 |
178 | ### Array & JSON Casting
179 |
180 | The `array` cast type is particularly useful when working with columns that are stored as serialized JSON. For example, if your database has a `JSON` or `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:
181 |
182 | 'array',
197 | ];
198 | }
199 |
200 | 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:
201 |
202 | $user = App\User::find(1);
203 |
204 | $options = $user->options;
205 |
206 | $options['key'] = 'value';
207 |
208 | $user->options = $options;
209 |
210 | $user->save();
211 |
--------------------------------------------------------------------------------
/eloquent-serialization.md:
--------------------------------------------------------------------------------
1 | # Eloquent: Serialization
2 |
3 | - [Introduction](#introduction)
4 | - [Serializing Models & Collections](#serializing-models-and-collections)
5 | - [Serializing To Arrays](#serializing-to-arrays)
6 | - [Serializing To JSON](#serializing-to-json)
7 | - [Hiding Attributes From JSON](#hiding-attributes-from-json)
8 | - [Appending Values To JSON](#appending-values-to-json)
9 |
10 |
11 | ## Introduction
12 |
13 | 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.
14 |
15 |
16 | ## Serializing Models & Collections
17 |
18 |
19 | ### Serializing To Arrays
20 |
21 | To convert a model and its loaded [relationships](/docs/{{version}}/eloquent-relationships) to an array, you should use the `toArray` method. This method is recursive, so all attributes and all relations (including the relations of relations) will be converted to arrays:
22 |
23 | $user = App\User::with('roles')->first();
24 |
25 | return $user->toArray();
26 |
27 | You may also convert entire [collections](/docs/{{version}}/eloquent-collections) of models to arrays:
28 |
29 | $users = App\User::all();
30 |
31 | return $users->toArray();
32 |
33 |
34 | ### Serializing To JSON
35 |
36 | To convert a model to JSON, you should use the `toJson` method. Like `toArray`, the `toJson` method is recursive, so all attributes and relations will be converted to JSON:
37 |
38 | $user = App\User::find(1);
39 |
40 | return $user->toJson();
41 |
42 | Alternatively, you may cast a model or collection to a string, which will automatically call the `toJson` method on the model or collection:
43 |
44 | $user = App\User::find(1);
45 |
46 | return (string) $user;
47 |
48 | 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:
49 |
50 | Route::get('users', function () {
51 | return App\User::all();
52 | });
53 |
54 |
55 | ## Hiding Attributes From JSON
56 |
57 | 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 to your model:
58 |
59 | {note} When hiding relationships, use the relationship's method name, not its dynamic property name.
76 |
77 | 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. All other attributes will be hidden when the model is converted to an array or JSON:
78 |
79 | makeVisible('attribute')->toArray();
100 |
101 | Likewise, if you would like to make some typically visible attributes hidden on a given model instance, you may use the `makeHidden` method.
102 |
103 | return $user->makeHidden('attribute')->toArray();
104 |
105 |
106 | ## Appending Values To JSON
107 |
108 | Occasionally, when casting models to an array or JSON, you may wish to add attributes that do not have a corresponding column in your database. To do so, first define an [accessor](/docs/{{version}}/eloquent-mutators) for the value:
109 |
110 | attributes['admin'] == 'yes';
126 | }
127 | }
128 |
129 | After creating the accessor, add the attribute name to the `appends` property on the model. Note that attribute names are typically referenced in "snake case", even though the accessor is defined using "camel case":
130 |
131 |
8 | ## Introduction
9 |
10 | Laravel's encrypter uses OpenSSL to provide AES-256 and AES-128 encryption. You are strongly encouraged to use Laravel's built-in encryption facilities and not attempt to roll your own "home grown" encryption algorithms. All of Laravel's encrypted values are signed using a message authentication code (MAC) so that their underlying value can not be modified once encrypted.
11 |
12 |
13 | ## Configuration
14 |
15 | Before using Laravel's encrypter, you must set a `key` option in your `config/app.php` configuration file. You should use the `php artisan key:generate` command to generate this key since this Artisan command will use PHP's secure random bytes generator to build your key. If this value is not properly set, all values encrypted by Laravel will be insecure.
16 |
17 |
18 | ## Using The Encrypter
19 |
20 | #### Encrypting A Value
21 |
22 | You may encrypt a value using the `encrypt` helper. 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:
23 |
24 | fill([
46 | 'secret' => encrypt($request->secret)
47 | ])->save();
48 | }
49 | }
50 |
51 | > {note} Encrypted values are passed through `serialize` during encryption, which allows for encryption of objects and arrays. Thus, non-PHP clients receiving encrypted values will need to `unserialize` the data.
52 |
53 | #### Decrypting A Value
54 |
55 | You may decrypt values using the `decrypt` helper. If the value can not be properly decrypted, such as when the MAC is invalid, an `Illuminate\Contracts\Encryption\DecryptException` will be thrown:
56 |
57 | use Illuminate\Contracts\Encryption\DecryptException;
58 |
59 | try {
60 | $decrypted = decrypt($encryptedValue);
61 | } catch (DecryptException $e) {
62 | //
63 | }
64 |
--------------------------------------------------------------------------------
/envoy.md:
--------------------------------------------------------------------------------
1 | # Envoy Task Runner
2 |
3 | - [Introduction](#introduction)
4 | - [Installation](#installation)
5 | - [Writing Tasks](#writing-tasks)
6 | - [Setup](#setup)
7 | - [Variables](#variables)
8 | - [Stories](#stories)
9 | - [Multiple Servers](#multiple-servers)
10 | - [Running Tasks](#running-tasks)
11 | - [Confirming Task Execution](#confirming-task-execution)
12 | - [Notifications](#notifications)
13 | - [Slack](#slack)
14 |
15 |
16 | ## Introduction
17 |
18 | [Laravel Envoy](https://github.com/laravel/envoy) provides a clean, minimal syntax for defining common tasks you run on your remote servers. Using Blade style syntax, you can easily setup tasks for deployment, Artisan commands, and more. Currently, Envoy only supports the Mac and Linux operating systems.
19 |
20 |
21 | ### Installation
22 |
23 | First, install Envoy using the Composer `global require` command:
24 |
25 | composer global require "laravel/envoy=~1.0"
26 |
27 | Since global Composer libraries can sometimes cause package version conflicts, you may wish to consider using `cgr`, which is a drop-in replacement for the `composer global require` command. The `cgr` library's installation instructions can be [found on GitHub](https://github.com/consolidation-org/cgr).
28 |
29 | > {note} Make sure to place the `~/.composer/vendor/bin` directory in your PATH so the `envoy` executable is found when running the `envoy` command in your terminal.
30 |
31 | #### Updating Envoy
32 |
33 | You may also use Composer to keep your Envoy installation up to date. Issuing the the `composer global update` command will update all of your globally installed Composer packages:
34 |
35 | composer global update
36 |
37 |
38 | ## Writing Tasks
39 |
40 | 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:
41 |
42 | @servers(['web' => ['user@192.168.1.1']])
43 |
44 | @task('foo', ['on' => 'web'])
45 | ls -la
46 | @endtask
47 |
48 | 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 should run on your server when the task is executed.
49 |
50 | You can force a script to run locally by specifying the server's IP address as `127.0.0.1`:
51 |
52 | @servers(['localhost' => '127.0.0.1'])
53 |
54 |
55 | ### Setup
56 |
57 | Sometimes, you may need to execute some PHP code before executing your Envoy tasks. You may use the ```@setup``` directive to declare variables and do other general PHP work before any of your other tasks are executed:
58 |
59 | @setup
60 | $now = new DateTime();
61 |
62 | $environment = isset($env) ? $env : "testing";
63 | @endsetup
64 |
65 | If you need to require other PHP files before your task is executed, you may use the `@include` directive at the top of your `Envoy.blade.php` file:
66 |
67 | @include('vendor/autoload.php')
68 |
69 | @task('foo')
70 | # ...
71 | @endtask
72 |
73 |
74 | ### Variables
75 |
76 | If needed, you may pass option values into Envoy tasks using the command line:
77 |
78 | envoy run deploy --branch=master
79 |
80 | You may use access the options in your tasks via Blade's "echo" syntax. Of course, you may also use `if` statements and loops within your tasks. For example, let's verify the presence of the `$branch` variable before executing the `git pull` command:
81 |
82 | @servers(['web' => '192.168.1.1'])
83 |
84 | @task('deploy', ['on' => 'web'])
85 | cd site
86 |
87 | @if ($branch)
88 | git pull origin {{ $branch }}
89 | @endif
90 |
91 | php artisan migrate
92 | @endtask
93 |
94 |
95 | ### Stories
96 |
97 | Stories group a set of tasks under a single, convenient name, allowing you to group small, focused tasks into large tasks. For instance, a `deploy` story may run the `git` and `composer` tasks by listing the task names within its definition:
98 |
99 | @servers(['web' => '192.168.1.1'])
100 |
101 | @story('deploy')
102 | git
103 | composer
104 | @endstory
105 |
106 | @task('git')
107 | git pull origin master
108 | @endtask
109 |
110 | @task('composer')
111 | composer install
112 | @endtask
113 |
114 | Once the story has been written, you may run it just like a typical task:
115 |
116 | envoy run deploy
117 |
118 |
119 | ### Multiple Servers
120 |
121 | Envoy allows you to 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, list each of the servers in the task's `on` array:
122 |
123 | @servers(['web-1' => '192.168.1.1', 'web-2' => '192.168.1.2'])
124 |
125 | @task('deploy', ['on' => ['web-1', 'web-2']])
126 | cd site
127 | git pull origin {{ $branch }}
128 | php artisan migrate
129 | @endtask
130 |
131 | #### Parallel Execution
132 |
133 | By default, tasks will be executed on each server serially. In other words, a task will finish running on the first server before proceeding to execute on the second server. If you would like to run a task across multiple servers in parallel, add the `parallel` option to your task declaration:
134 |
135 | @servers(['web-1' => '192.168.1.1', 'web-2' => '192.168.1.2'])
136 |
137 | @task('deploy', ['on' => ['web-1', 'web-2'], 'parallel' => true])
138 | cd site
139 | git pull origin {{ $branch }}
140 | php artisan migrate
141 | @endtask
142 |
143 |
144 | ## Running Tasks
145 |
146 | To run a task or story that is defined in your `Envoy.blade.php` file, execute Envoy's `run` command, passing the name of the task or story you would like to execute. Envoy will run the task and display the output from the servers as the task is running:
147 |
148 | envoy run task
149 |
150 |
151 | ### Confirming Task Execution
152 |
153 | If you would like to be prompted for confirmation before running a given task on your servers, you should add the `confirm` directive to your task declaration. This option is particularly useful for destructive operations:
154 |
155 | @task('deploy', ['on' => 'web', 'confirm' => true])
156 | cd site
157 | git pull origin {{ $branch }}
158 | php artisan migrate
159 | @endtask
160 |
161 |
162 |
163 | ## Notifications
164 |
165 |
166 | ### Slack
167 |
168 | Envoy also supports sending notifications to [Slack](https://slack.com) after each task is executed. The `@slack` directive accepts a Slack hook URL and a channel name. You may retrieve your webhook URL by creating an "Incoming WebHooks" integration in your Slack control panel. You should pass the entire webhook URL into the `@slack` directive:
169 |
170 | @after
171 | @slack('webhook-url', '#bots')
172 | @endafter
173 |
174 | You may provide one of the following as the channel argument:
175 |
176 |
177 | - To send the notification to a channel: `#channel`
178 | - To send the notification to a user: `@user`
179 |
180 |
181 |
--------------------------------------------------------------------------------
/errors.md:
--------------------------------------------------------------------------------
1 | # Errors & Logging
2 |
3 | - [Introduction](#introduction)
4 | - [Configuration](#configuration)
5 | - [Error Detail](#error-detail)
6 | - [Log Storage](#log-storage)
7 | - [Log Severity Levels](#log-severity-levels)
8 | - [Custom Monolog Configuration](#custom-monolog-configuration)
9 | - [The Exception Handler](#the-exception-handler)
10 | - [Report Method](#report-method)
11 | - [Render Method](#render-method)
12 | - [HTTP Exceptions](#http-exceptions)
13 | - [Custom HTTP Error Pages](#custom-http-error-pages)
14 | - [Logging](#logging)
15 |
16 |
17 | ## Introduction
18 |
19 | When you start a new Laravel project, error and exception handling is already configured for you. The `App\Exceptions\Handler` class is where all exceptions triggered by your application are logged and then rendered back to the user. We'll dive deeper into this class throughout this documentation.
20 |
21 | For logging, Laravel utilizes the [Monolog](https://github.com/Seldaek/monolog) library, which provides support for a variety of powerful log handlers. Laravel configures several of these handlers for you, allowing you to choose between a single log file, rotating log files, or writing error information to the system log.
22 |
23 |
24 | ## Configuration
25 |
26 |
27 | ### Error Detail
28 |
29 | The `debug` option in your `config/app.php` configuration file determines how much information about an error is actually displayed to the user. By default, this option is set to respect the value of the `APP_DEBUG` environment variable, which is stored in your `.env` file.
30 |
31 | For local development, you should set the `APP_DEBUG` environment variable to `true`. In your production environment, this value should always be `false`. If the value is set to `true` in production, you risk exposing sensitive configuration values to your application's end users.
32 |
33 |
34 | ### Log Storage
35 |
36 | Out of the box, Laravel supports writing log information to `single` files, `daily` files, the `syslog`, and the `errorlog`. To configure which storage mechanism Laravel uses, you should modify the `log` option in your `config/app.php` configuration file. For example, if you wish to use daily log files instead of a single file, you should set the `log` value in your `app` configuration file to `daily`:
37 |
38 | 'log' => 'daily'
39 |
40 | #### Maximum Daily Log Files
41 |
42 | When using the `daily` log mode, Laravel will only retain five days of log files by default. If you want to adjust the number of retained files, you may add a `log_max_files` configuration value to your `app` configuration file:
43 |
44 | 'log_max_files' => 30
45 |
46 |
47 | ### Log Severity Levels
48 |
49 | When using Monolog, log messages may have different levels of severity. By default, Laravel writes all log levels to storage. However, in your production environment, you may wish to configure the minimum severity that should be logged by adding the `log_level` option to your `app.php` configuration file.
50 |
51 | Once this option has been configured, Laravel will log all levels greater than or equal to the specified severity. For example, a default `log_level` of `error` will log **error**, **critical**, **alert**, and **emergency** messages:
52 |
53 | 'log_level' => env('APP_LOG_LEVEL', 'error'),
54 |
55 | > {tip} Monolog recognizes the following severity levels - from least severe to most severe: `debug`, `info`, `notice`, `warning`, `error`, `critical`, `alert`, `emergency`.
56 |
57 |
58 | ### Custom Monolog Configuration
59 |
60 | 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:
61 |
62 | $app->configureMonologUsing(function($monolog) {
63 | $monolog->pushHandler(...);
64 | });
65 |
66 | return $app;
67 |
68 |
69 | ## The Exception Handler
70 |
71 |
72 | ### The Report Method
73 |
74 | 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. The `report` method is used to log exceptions or send them to an external service like [Bugsnag](https://bugsnag.com) or [Sentry](https://github.com/getsentry/sentry-laravel). 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.
75 |
76 | For example, if you need to report different types of exceptions in different ways, you may use the PHP `instanceof` comparison operator:
77 |
78 | /**
79 | * Report or log an exception.
80 | *
81 | * This is a great spot to send exceptions to Sentry, Bugsnag, etc.
82 | *
83 | * @param \Exception $exception
84 | * @return void
85 | */
86 | public function report(Exception $exception)
87 | {
88 | if ($exception instanceof CustomException) {
89 | //
90 | }
91 |
92 | return parent::report($exception);
93 | }
94 |
95 | #### Ignoring Exceptions By Type
96 |
97 | The `$dontReport` property of the exception handler contains an array of exception types that will not be logged. For example, exceptions resulting from 404 errors, as well as several other types of errors, are not written to your log files. You may add other exception types to this array as needed:
98 |
99 | /**
100 | * A list of the exception types that should not be reported.
101 | *
102 | * @var array
103 | */
104 | protected $dontReport = [
105 | \Illuminate\Auth\AuthenticationException::class,
106 | \Illuminate\Auth\Access\AuthorizationException::class,
107 | \Symfony\Component\HttpKernel\Exception\HttpException::class,
108 | \Illuminate\Database\Eloquent\ModelNotFoundException::class,
109 | \Illuminate\Validation\ValidationException::class,
110 | ];
111 |
112 |
113 | ### The Render Method
114 |
115 | 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:
116 |
117 | /**
118 | * Render an exception into an HTTP response.
119 | *
120 | * @param \Illuminate\Http\Request $request
121 | * @param \Exception $exception
122 | * @return \Illuminate\Http\Response
123 | */
124 | public function render($request, Exception $exception)
125 | {
126 | if ($exception instanceof CustomException) {
127 | return response()->view('errors.custom', [], 500);
128 | }
129 |
130 | return parent::render($request, $exception);
131 | }
132 |
133 |
134 | ## HTTP Exceptions
135 |
136 | 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, you may use the `abort` helper:
137 |
138 | abort(404);
139 |
140 | The `abort` helper will immediately raise an exception which will be rendered by the exception handler. Optionally, you may provide the response text:
141 |
142 | abort(403, 'Unauthorized action.');
143 |
144 |
145 | ### Custom HTTP Error Pages
146 |
147 | Laravel makes it easy to display 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. The views within this directory should be named to match the HTTP status code they correspond to. The `HttpException` instance raised by the `abort` function will be passed to the view as an `$exception` variable.
148 |
149 |
150 | ## Logging
151 |
152 | Laravel provides a simple abstraction layer on top of the powerful [Monolog](http://github.com/seldaek/monolog) library. By default, Laravel is configured to create a log file for your application in the `storage/logs` directory. You may write information to the logs using the `Log` [facade](/docs/{{version}}/facades):
153 |
154 | User::findOrFail($id)]);
175 | }
176 | }
177 |
178 | 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**.
179 |
180 | Log::emergency($message);
181 | Log::alert($message);
182 | Log::critical($message);
183 | Log::error($message);
184 | Log::warning($message);
185 | Log::notice($message);
186 | Log::info($message);
187 | Log::debug($message);
188 |
189 | #### Contextual Information
190 |
191 | 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:
192 |
193 | Log::info('User failed to login.', ['id' => $user->id]);
194 |
195 | #### Accessing The Underlying Monolog Instance
196 |
197 | 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:
198 |
199 | $monolog = Log::getMonolog();
200 |
--------------------------------------------------------------------------------
/frontend.md:
--------------------------------------------------------------------------------
1 | # JavaScript & CSS
2 |
3 | - [Introduction](#introduction)
4 | - [Writing CSS](#writing-css)
5 | - [Writing JavaScript](#writing-javascript)
6 | - [Writing Vue Components](#writing-vue-components)
7 |
8 |
9 | ## Introduction
10 |
11 | While Laravel does not dictate which JavaScript or CSS pre-processors you use, it does provide a basic starting point using [Bootstrap](http://getbootstrap.com) and [Vue](https://vuejs.org) that will be helpful for many applications. By default, Laravel uses [NPM](https://npmjs.org) to install both of these frontend packages.
12 |
13 | #### CSS
14 |
15 | [Laravel Elixir](/docs/{{version}}/elixir) provides a clean, expressive API over compiling SASS or Less, which are extensions of plain CSS that add variables, mixins, and other powerful features that make working with CSS much more enjoyable.
16 |
17 | In this document, we will briefly discuss CSS compilation in general; however, you should consult the full [Laravel Elixir documentation](/docs/{{version}}/elixir) for more information on compiling SASS or Less.
18 |
19 | #### JavaScript
20 |
21 | Laravel does not require you to use a specific JavaScript framework or library to build your applications. In fact, you don't have to use JavaScript at all. However, Laravel does include some basic scaffolding to make it easier to get started writing modern JavaScript using the [Vue](https://vuejs.org) library. Vue provides an expressive API for building robust JavaScript applications using components.
22 |
23 |
24 | ## Writing CSS
25 |
26 | The Laravel `package.json` file includes the `bootstrap-sass` package to help you get started prototyping your application's frontend using Bootstrap. However, feel free to add or remove packages from the `package.json` file as needed for your own application. You are not required to use the Bootstrap framework to build your Laravel application - it is simply provided as a good starting point for those who choose to use it.
27 |
28 | Before compiling your CSS, install your project's frontend dependencies using NPM:
29 |
30 | npm install
31 |
32 | Once the dependencies have been installed using `npm install`, you can compile your SASS files to plain CSS using [Gulp](http://gulpjs.com/). The `gulp` command will process the instructions in your `gulpfile.js` file. Typically, your compiled CSS will be placed in the `public/css` directory:
33 |
34 | gulp
35 |
36 | The default `gulpfile.js` included with Laravel will compile the `resources/assets/sass/app.scss` SASS file. This `app.scss` file imports a file of SASS variables and loads Bootstrap, which provides a good starting point for most applications. Feel free to customize the `app.scss` file however you wish or even use an entirely different pre-processor by [configuring Laravel Elixir](/docs/{{version}}/elixir).
37 |
38 |
39 | ## Writing JavaScript
40 |
41 | All of the JavaScript dependencies required by your application can be found in the `package.json` file in the project's root directory. This file is similar to a `composer.json` file except it specifies JavaScript dependencies instead of PHP dependencies. You can install these dependencies using the [Node package manager (NPM)](https://npmjs.org):
42 |
43 | npm install
44 |
45 | By default, the Laravel `package.json` file includes a few packages such as `vue` and `vue-resource` to help you get started building your JavaScript application. Feel free to add or remove from the `package.json` file as needed for your own application.
46 |
47 | Once the packages are installed, you can use the `gulp` command to [compile your assets](/docs/{{version}}/elixir). Gulp is a command-line build system for JavaScript. When you run the `gulp` command, Gulp will execute the instructions in your `gulpfile.js` file:
48 |
49 | gulp
50 |
51 | By default, the Laravel `gulpfile.js` file compiles your SASS and the `resources/assets/js/app.js` file. Within the `app.js` file you may register your Vue components or, if you prefer a different framework, configure your own JavaScript application. Your compiled JavaScript will typically be placed in the `public/js` directory.
52 |
53 | > {tip} The `app.js` file will load the `resources/assets/js/bootstrap.js` file which bootstraps and configures Vue, Vue Resource, jQuery, and all other JavaScript dependencies. If you have additional JavaScript dependencies to configure, you may do so in this file.
54 |
55 |
56 | ### Writing Vue Components
57 |
58 | By default, fresh Laravel applications contain an `Example.vue` Vue component located in the `resources/assets/js/components` directory. The `Example.vue` file is an example of a [single file Vue component](http://vuejs.org/guide/single-file-components.html) which defines its JavaScript and HTML template in the same file. Single file components provide a very convenient approach to building JavaScript driven applications. The example component is registered in your `app.js` file:
59 |
60 | Vue.component('example', require('./components/Example.vue'));
61 |
62 | To use the component in your application, you may simply drop it into one of your HTML templates. For example, after running the `make:auth` Artisan command to scaffold your application's authentication and registration screens, you could drop the component into the `home.blade.php` Blade template:
63 |
64 | @extends('layouts.app')
65 |
66 | @section('content')
67 |
68 | @endsection
69 |
70 | > {tip} Remember, you should run the `gulp` command each time you change a Vue component. Or, you may run the `gulp watch` command to monitor and automatically recompile your components each time they are modified.
71 |
72 | Of course, if you are interested in learning more about writing Vue components, you should read the [Vue documentation](http://vuejs.org/guide/), which provides a thorough, easy-to-read overview of the entire Vue framework.
73 |
--------------------------------------------------------------------------------
/hashing.md:
--------------------------------------------------------------------------------
1 | # Hashing
2 |
3 | - [Introduction](#introduction)
4 | - [Basic Usage](#basic-usage)
5 |
6 |
7 | ## Introduction
8 |
9 | The Laravel `Hash` [facade](/docs/{{version}}/facades) provides secure Bcrypt hashing for storing user passwords. If you are using the built-in `LoginController` and `RegisterController` classes that are included with your Laravel application, they will automatically use Bcrypt for registration and authentication.
10 |
11 | > {tip} 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 | user()->fill([
39 | 'password' => Hash::make($request->newPassword)
40 | ])->save();
41 | }
42 | }
43 |
44 | #### Verifying A Password Against A Hash
45 |
46 | The `check` method allows you to verify that a given plain-text string corresponds to a given hash. However, if you are using the `LoginController` [included with Laravel](/docs/{{version}}/authentication), you will probably not need to use this directly, as this controller automatically calls this method:
47 |
48 | if (Hash::check('plain-text', $hashedPassword)) {
49 | // The passwords match...
50 | }
51 |
52 | #### Checking If A Password Needs To Be Rehashed
53 |
54 | The `needsRehash` function allows you to determine if the work factor used by the hasher has changed since the password was hashed:
55 |
56 | if (Hash::needsRehash($hashed)) {
57 | $hashed = Hash::make('plain-text');
58 | }
59 |
--------------------------------------------------------------------------------
/html.md:
--------------------------------------------------------------------------------
1 | # Forms & HTML
2 |
3 | - [Opening A Form](#opening-a-form)
4 | - [CSRF Protection](#csrf-protection)
5 | - [Form Model Binding](#form-model-binding)
6 | - [Labels](#labels)
7 | - [Text, Text Area, Password & Hidden Fields](#text)
8 | - [Checkboxes and Radio Buttons](#checkboxes-and-radio-buttons)
9 | - [File Input](#file-input)
10 | - [Number Input](#number)
11 | - [Drop-Down Lists](#drop-down-lists)
12 | - [Buttons](#buttons)
13 | - [Custom Macros](#custom-macros)
14 | - [Generating URLs](#generating-urls)
15 |
16 |
17 | ## Opening A Form
18 |
19 | #### Opening A Form
20 |
21 | {{ Form::open(array('url' => 'foo/bar')) }}
22 | //
23 | {{ Form::close() }}
24 |
25 | By default, a `POST` method will be assumed; however, you are free to specify another method:
26 |
27 | echo Form::open(array('url' => 'foo/bar', 'method' => 'put'))
28 |
29 | > **Note:** Since HTML forms only support `POST` and `GET`, `PUT` and `DELETE` methods will be spoofed by automatically adding a `_method` hidden field to your form.
30 |
31 | You may also open forms that point to named routes or controller actions:
32 |
33 | echo Form::open(array('route' => 'route.name'))
34 |
35 | echo Form::open(array('action' => 'Controller@method'))
36 |
37 | You may pass in route parameters as well:
38 |
39 | echo Form::open(array('route' => array('route.name', $user->id)))
40 |
41 | echo Form::open(array('action' => array('Controller@method', $user->id)))
42 |
43 | If your form is going to accept file uploads, add a `files` option to your array:
44 |
45 | echo Form::open(array('url' => 'foo/bar', 'files' => true))
46 |
47 |
48 | ## CSRF Protection
49 |
50 | #### Adding The CSRF Token To A Form
51 |
52 | Laravel provides an easy method of protecting your application from cross-site request forgeries. First, a random token is placed in your user's session. If you use the `Form::open` method with `POST`, `PUT` or `DELETE` the CSRF token will be added to your forms as a hidden field automatically. Alternatively, if you wish to generate the HTML for the hidden CSRF field, you may use the `token` method:
53 |
54 | echo Form::token();
55 |
56 | #### Attaching The CSRF Filter To A Route
57 |
58 | Route::post('profile', array('before' => 'csrf', function()
59 | {
60 | //
61 | }));
62 |
63 |
64 | ## Form Model Binding
65 |
66 | #### Opening A Model Form
67 |
68 | Often, you will want to populate a form based on the contents of a model. To do so, use the `Form::model` method:
69 |
70 | echo Form::model($user, array('route' => array('user.update', $user->id)))
71 |
72 | Now, when you generate a form element, like a text input, the model's value matching the field's name will automatically be set as the field value. So, for example, for a text input named `email`, the user model's `email` attribute would be set as the value. However, there's more! If there is an item in the Session flash data matching the input name, that will take precedence over the model's value. So, the priority looks like this:
73 |
74 | 1. Session Flash Data (Old Input)
75 | 2. Explicitly Passed Value
76 | 3. Model Attribute Data
77 |
78 | This allows you to quickly build forms that not only bind to model values, but easily re-populate if there is a validation error on the server!
79 |
80 | > **Note:** When using `Form::model`, be sure to close your form with `Form::close`!
81 |
82 |
83 | ## Labels
84 |
85 | #### Generating A Label Element
86 |
87 | echo Form::label('email', 'E-Mail Address');
88 |
89 | #### Specifying Extra HTML Attributes
90 |
91 | echo Form::label('email', 'E-Mail Address', array('class' => 'awesome'));
92 |
93 | > **Note:** After creating a label, any form element you create with a name matching the label name will automatically receive an ID matching the label name as well.
94 |
95 |
96 | ## Text, Text Area, Password & Hidden Fields
97 |
98 | #### Generating A Text Input
99 |
100 | echo Form::text('username');
101 |
102 | #### Specifying A Default Value
103 |
104 | echo Form::text('email', 'example@gmail.com');
105 |
106 | > **Note:** The *hidden* and *textarea* methods have the same signature as the *text* method.
107 |
108 | #### Generating A Password Input
109 |
110 | echo Form::password('password');
111 |
112 | #### Generating Other Inputs
113 |
114 | echo Form::email($name, $value = null, $attributes = array());
115 | echo Form::file($name, $attributes = array());
116 |
117 |
118 | ## Checkboxes and Radio Buttons
119 |
120 | #### Generating A Checkbox Or Radio Input
121 |
122 | echo Form::checkbox('name', 'value');
123 |
124 | echo Form::radio('name', 'value');
125 |
126 | #### Generating A Checkbox Or Radio Input That Is Checked
127 |
128 | echo Form::checkbox('name', 'value', true);
129 |
130 | echo Form::radio('name', 'value', true);
131 |
132 |
133 | ## Number
134 |
135 | #### Generating A Number Input
136 |
137 | echo Form::number('name', 'value');
138 |
139 |
140 | ## File Input
141 |
142 | #### Generating A File Input
143 |
144 | echo Form::file('image');
145 |
146 | > **Note:** The form must have been opened with the `files` option set to `true`.
147 |
148 |
149 | ## Drop-Down Lists
150 |
151 | #### Generating A Drop-Down List
152 |
153 | echo Form::select('size', array('L' => 'Large', 'S' => 'Small'));
154 |
155 | #### Generating A Drop-Down List With Selected Default
156 |
157 | echo Form::select('size', array('L' => 'Large', 'S' => 'Small'), 'S');
158 |
159 | #### Generating A Grouped List
160 |
161 | echo Form::select('animal', array(
162 | 'Cats' => array('leopard' => 'Leopard'),
163 | 'Dogs' => array('spaniel' => 'Spaniel'),
164 | ));
165 |
166 | #### Generating A Drop-Down List With A Range
167 |
168 | echo Form::selectRange('number', 10, 20);
169 |
170 | #### Generating A List With Month Names
171 |
172 | echo Form::selectMonth('month');
173 |
174 |
175 | ## Buttons
176 |
177 | #### Generating A Submit Button
178 |
179 | echo Form::submit('Click Me!');
180 |
181 | > **Note:** Need to create a button element? Try the *button* method. It has the same signature as *submit*.
182 |
183 |
184 | ## Custom Macros
185 |
186 | #### Registering A Form Macro
187 |
188 | It's easy to define your own custom Form class helpers called "macros". Here's how it works. First, simply register the macro with a given name and a Closure:
189 |
190 | Form::macro('myField', function()
191 | {
192 | return '';
193 | });
194 |
195 | Now you can call your macro using its name:
196 |
197 | #### Calling A Custom Form Macro
198 |
199 | echo Form::myField();
200 |
201 |
202 | ## Generating URLs
203 |
204 | For more information on generating URL's, check out the documentation on [helpers](/docs/helpers#urls).
205 |
--------------------------------------------------------------------------------
/installation.md:
--------------------------------------------------------------------------------
1 | # Installation
2 |
3 | - [Installation](#installation)
4 | - [Server Requirements](#server-requirements)
5 | - [Installing Laravel](#installing-laravel)
6 | - [Configuration](#configuration)
7 |
8 |
9 | ## Installation
10 |
11 |
12 | ### Server Requirements
13 |
14 | The Laravel framework has a few system requirements. Of course, all of these requirements are satisfied by the [Laravel Homestead](/docs/{{version}}/homestead) virtual machine, so it's highly recommended that you use Homestead as your local Laravel development environment.
15 |
16 | However, if you are not using Homestead, you will need to make sure your server meets the following requirements:
17 |
18 |
26 |
27 |
28 | ### Installing Laravel
29 |
30 | Laravel utilizes [Composer](http://getcomposer.org) to manage its dependencies. So, before using Laravel, make sure you have Composer installed on your machine.
31 |
32 | #### Via Laravel Installer
33 |
34 | First, download the Laravel installer using Composer:
35 |
36 | composer global require "laravel/installer"
37 |
38 | Make sure to place the `$HOME/.composer/vendor/bin` directory (or the equivalent directory for your OS) in your $PATH so the `laravel` executable can be located by your system.
39 |
40 | Once installed, the `laravel new` command will create a fresh Laravel installation in the directory you specify. For instance, `laravel new blog` will create a directory named `blog` containing a fresh Laravel installation with all of Laravel's dependencies already installed:
41 |
42 | laravel new blog
43 |
44 | #### Via Composer Create-Project
45 |
46 | Alternatively, you may also install Laravel by issuing the Composer `create-project` command in your terminal:
47 |
48 | composer create-project --prefer-dist laravel/laravel blog
49 |
50 | #### Local Development Server
51 |
52 | If you have PHP installed locally and you would like to use PHP's built-in development server to serve your application, you may use the `serve` Artisan command. This command will start a development server at `http://localhost:8000`:
53 |
54 | php artisan serve
55 |
56 | Of course, more robust local development options are available via [Homestead](/docs/{{version}}/homestead) and [Valet](/docs/{{version}}/valet).
57 |
58 |
59 | ### Configuration
60 |
61 | #### Public Directory
62 |
63 | After installing Laravel, you should configure your web server's document / web root to be the `public` directory. The `index.php` in this directory serves as the front controller for all HTTP requests entering your application.
64 |
65 | #### Configuration Files
66 |
67 | All of the configuration files for the Laravel framework are stored in the `config` directory. Each option is documented, so feel free to look through the files and get familiar with the options available to you.
68 |
69 | #### Directory Permissions
70 |
71 | After installing Laravel, you may need to configure some permissions. Directories within the `storage` and the `bootstrap/cache` directories should be writable by your web server or Laravel will not run. If you are using the [Homestead](/docs/{{version}}/homestead) virtual machine, these permissions should already be set.
72 |
73 | #### Application Key
74 |
75 | The next thing you should do after installing Laravel is set your application key to a random string. If you installed Laravel via Composer or the Laravel installer, this key has already been set for you by the `php artisan key:generate` command.
76 |
77 | Typically, this string should be 32 characters long. The key can be set in the `.env` environment file. If you have not renamed the `.env.example` file to `.env`, you should do that now. **If the application key is not set, your user sessions and other encrypted data will not be secure!**
78 |
79 | #### Additional Configuration
80 |
81 | Laravel needs almost no other configuration out of the box. You are free to get started developing! However, you may wish to review the `config/app.php` file and its documentation. It contains several options such as `timezone` and `locale` that you may wish to change according to your application.
82 |
83 | You may also want to configure a few additional components of Laravel, such as:
84 |
85 |
94 |
95 | {{ $users->links() }}
96 |
97 | The `links` 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 `links` method is compatible with the [Bootstrap CSS framework](https://getbootstrap.com).
98 |
99 | #### Customizing The Paginator URI
100 |
101 | 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:
102 |
103 | Route::get('users', function () {
104 | $users = App\User::paginate(15);
105 |
106 | $users->setPath('custom/url');
107 |
108 | //
109 | });
110 |
111 | #### Appending To Pagination Links
112 |
113 | You may append 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`:
114 |
115 | {{ $users->appends(['sort' => 'votes'])->links() }}
116 |
117 | 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:
118 |
119 | {{ $users->fragment('foo')->links() }}
120 |
121 |
122 | ### Converting Results To JSON
123 |
124 | The Laravel paginator result classes implement the `Illuminate\Contracts\Support\Jsonable` Interface contract and expose the `toJson` method, so it's very easy to convert your pagination results to JSON. You may also convert a paginator instance to JSON by simply returning it from a route or controller action:
125 |
126 | Route::get('users', function () {
127 | return App\User::paginate();
128 | });
129 |
130 | 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:
131 |
132 | {
133 | "total": 50,
134 | "per_page": 15,
135 | "current_page": 1,
136 | "last_page": 4,
137 | "next_page_url": "http://laravel.app?page=2",
138 | "prev_page_url": null,
139 | "from": 1,
140 | "to": 15,
141 | "data":[
142 | {
143 | // Result Object
144 | },
145 | {
146 | // Result Object
147 | }
148 | ]
149 | }
150 |
151 |
152 | ## Customizing The Pagination View
153 |
154 | By default, the views rendered to display the pagination links are compatible with the Bootstrap CSS framework. However, if you are not using Bootstrap, you are free to define your own views to render these links. When calling the `links` method on a paginator instance, pass the view name as the first argument to the method:
155 |
156 | {{ $paginator->links('view.name') }}
157 |
158 | However, the easiest way to customize the pagination views is by exporting them to your `resources/views/vendor` directory using the `vendor:publish` command:
159 |
160 | php artisan vendor:publish --tag=laravel-pagination
161 |
162 | This command will place the views in the `resources/views/vendor/pagination` directory. The `default.blade.php` file within this directory corresponds to the default pagination view. Simply edit this file to modify the pagination HTML.
163 |
164 |
165 | ## Paginator Instance Methods
166 |
167 | Each paginator instance provides additional pagination information via the following methods:
168 |
169 | - `$results->count()`
170 | - `$results->currentPage()`
171 | - `$results->firstItem()`
172 | - `$results->hasMorePages()`
173 | - `$results->lastItem()`
174 | - `$results->lastPage() (Not available when using simplePaginate)`
175 | - `$results->nextPageUrl()`
176 | - `$results->perPage()`
177 | - `$results->previousPageUrl()`
178 | - `$results->total() (Not available when using simplePaginate)`
179 | - `$results->url($page)`
180 |
--------------------------------------------------------------------------------
/passwords.md:
--------------------------------------------------------------------------------
1 | # Resetting Passwords
2 |
3 | - [Introduction](#introduction)
4 | - [Database Considerations](#resetting-database)
5 | - [Routing](#resetting-routing)
6 | - [Views](#resetting-views)
7 | - [After Resetting Passwords](#after-resetting-passwords)
8 | - [Customization](#password-customization)
9 |
10 |
11 | ## Introduction
12 |
13 | > {tip} **Want to get started fast?** Just run `php artisan make:auth` in a fresh Laravel application and navigate your browser to `http://your-app.dev/register` or any other URL that is assigned to your application. This single command will take care of scaffolding your entire authentication system, including resetting passwords!
14 |
15 | Most web applications provide a way for users to reset their forgotten passwords. Rather than forcing you to re-implement this on each application, Laravel provides convenient methods for sending password reminders and performing password resets.
16 |
17 | > {note} Before using the password reset features of Laravel, your user must use the `Illuminate\Notifications\Notifiable` trait.
18 |
19 |
20 | ## Database Considerations
21 |
22 | To get started, verify that your `App\User` model implements the `Illuminate\Contracts\Auth\CanResetPassword` contract. Of course, the `App\User` model included with the framework already implements this interface, and uses the `Illuminate\Auth\Passwords\CanResetPassword` trait to include the methods needed to implement the interface.
23 |
24 | #### Generating The Reset Token Table Migration
25 |
26 | Next, a table must be created to store the password reset tokens. The migration for this table is included with Laravel out of the box, and resides in the `database/migrations` directory. So, all you need to do is run your database migrations:
27 |
28 | php artisan migrate
29 |
30 |
31 | ## Routing
32 |
33 | Laravel includes `Auth\ForgotPasswordController` and `Auth\ResetPasswordController` classes that contains the logic necessary to e-mail password reset links and reset user passwords. All of the routes needed to perform password resets may be generated using the `make:auth` Artisan command:
34 |
35 | php artisan make:auth
36 |
37 |
38 | ## Views
39 |
40 | Again, Laravel will generate all of the necessary views for password reset when the `make:auth` command is executed. These views are placed in `resources/views/auth/passwords`. You are free to customize them as needed for your application.
41 |
42 |
43 | ## After Resetting Passwords
44 |
45 | Once you have defined the routes and views to reset your user's passwords, you may simply access the route in your browser at `/password/reset`. The `ForgotPasswordController` included with the framework already includes the logic to send the password reset link e-mails, while the `ResetPasswordController` includes the logic to reset user passwords.
46 |
47 | After a password is reset, the user will automatically be logged into the application and redirected to `/home`. You can customize the post password reset redirect location by defining a `redirectTo` property on the `ResetPasswordController`:
48 |
49 | protected $redirectTo = '/dashboard';
50 |
51 | > {note} By default, password reset tokens expire after one hour. You may change this via the password reset `expire` option in your `config/auth.php` file.
52 |
53 |
54 | ## Customization
55 |
56 | #### Authentication Guard Customization
57 |
58 | In your `auth.php` configuration file, you may configure multiple "guards", which may be used to define authentication behavior for multiple user tables. You can customize the included `ResetPasswordController` to use the guard of your choice by overriding the `guard` method on the controller. This method should return a guard instance:
59 |
60 | use Illuminate\Support\Facades\Auth;
61 |
62 | protected function guard()
63 | {
64 | return Auth::guard('guard-name');
65 | }
66 |
67 | #### Password Broker Customization
68 |
69 | In your `auth.php` configuration file, you may configure multiple password "brokers", which may be used to reset passwords on multiple user tables. You can customize the included `ForgotPasswordController` and `ResetPasswordController` to use the broker of your choice by overriding the `broker` method:
70 |
71 | use Illuminate\Support\Facades\Password;
72 |
73 | /**
74 | * Get the broker to be used during password reset.
75 | *
76 | * @return PasswordBroker
77 | */
78 | protected function broker()
79 | {
80 | return Password::broker('name');
81 | }
82 |
83 | #### Reset Email Customization
84 |
85 | You may easily modify the notification class used to send the password reset link to the user. To get started, override the `sendPasswordResetNotification` method on your `User` model. Within this method, you may send the notification using any notification class you choose. The password reset `$token` is the first argument received by the method:
86 |
87 | /**
88 | * Send the password reset notification.
89 | *
90 | * @param string $token
91 | * @return void
92 | */
93 | public function sendPasswordResetNotification($token)
94 | {
95 | $this->notify(new ResetPasswordNotification($token));
96 | }
97 |
98 |
--------------------------------------------------------------------------------
/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 these 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. Most service providers contain a `register` and a `boot` method. Within the `register` method, you should **only bind things into the [service container](/docs/{{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 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](/docs/{{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 accidentally use a service that is provided by a service provider which has not loaded yet.
34 |
35 | Let's take a look at a basic service provider. Within any of your service provider methods, you always have access to the `$app` property which provides access to the service container:
36 |
37 | app->singleton(Connection::class, 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\Connection` in the service container. If you don't understand how the service container works, check out [its documentation](/docs/{{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 | #### Boot Method Dependency Injection
88 |
89 | You may type-hint dependencies for your service provider's `boot` method. The [service container](/docs/{{version}}/container) will automatically inject any dependencies you need:
90 |
91 | use Illuminate\Contracts\Routing\ResponseFactory;
92 |
93 | public function boot(ResponseFactory $response)
94 | {
95 | $response->macro('caps', function ($value) {
96 | //
97 | });
98 | }
99 |
100 |
101 | ## Registering Providers
102 |
103 | All service providers are registered in the `config/app.php` configuration file. This file contains a `providers` array where you can list the class 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.
104 |
105 | To register your provider, simply add it to the array:
106 |
107 | 'providers' => [
108 | // Other Service Providers
109 |
110 | App\Providers\ComposerServiceProvider::class,
111 | ],
112 |
113 |
114 | ## Deferred Providers
115 |
116 | If your provider is **only** registering bindings in the [service container](/docs/{{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.
117 |
118 | 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.
119 |
120 | To defer the loading of a provider, set the `defer` property to `true` and define a `provides` method. The `provides` method should return the service container bindings registered by the provider:
121 |
122 | app->singleton(Connection::class, function ($app) {
146 | return new Connection($app['config']['riak']);
147 | });
148 | }
149 |
150 | /**
151 | * Get the services provided by the provider.
152 | *
153 | * @return array
154 | */
155 | public function provides()
156 | {
157 | return [Connection::class];
158 | }
159 |
160 | }
161 |
--------------------------------------------------------------------------------
/redirects.md:
--------------------------------------------------------------------------------
1 | # HTTP Redirects
2 |
3 | - [Creating Redirects](#creating-redirects)
4 | - [Redirecting To Named Routes](#redirecting-named-routes)
5 | - [Redirecting To Controller Actions](#redirecting-controller-actions)
6 | - [Redirecting With Flashed Session Data](#redirecting-with-flashed-session-data)
7 |
8 |
9 | ## Creating Redirects
10 |
11 | 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:
12 |
13 | Route::get('dashboard', function () {
14 | return redirect('home/dashboard');
15 | });
16 |
17 | Sometimes you may wish to redirect the user to their previous location, such as when a submitted form is invalid. You may do so by using the global `back` helper function. Since this feature utilizes the [session](/docs/{{version}}/session), make sure the route calling the `back` function is using the `web` middleware group or has all of the session middleware applied:
18 |
19 | Route::post('user/profile', function () {
20 | // Validate the request...
21 |
22 | return back()->withInput();
23 | });
24 |
25 |
26 | ## Redirecting To Named Routes
27 |
28 | 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:
29 |
30 | return redirect()->route('login');
31 |
32 | If your route has parameters, you may pass them as the second argument to the `route` method:
33 |
34 | // For a route with the following URI: profile/{id}
35 |
36 | return redirect()->route('profile', ['id' => 1]);
37 |
38 | #### Populating Parameters Via Eloquent Models
39 |
40 | 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:
41 |
42 | // For a route with the following URI: profile/{id}
43 |
44 | return redirect()->route('profile', [$user]);
45 |
46 | If you would like to customize the value that is placed in the route parameter, you should override the `getRouteKey` method on your Eloquent model:
47 |
48 | /**
49 | * Get the value of the model's route key.
50 | *
51 | * @return mixed
52 | */
53 | public function getRouteKey()
54 | {
55 | return $this->slug;
56 | }
57 |
58 |
59 | ## Redirecting To Controller Actions
60 |
61 | You may also generate redirects to [controller actions](/docs/{{version}}/controllers). To do so, 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 base controller namespace:
62 |
63 | return redirect()->action('HomeController@index');
64 |
65 | If your controller route requires parameters, you may pass them as the second argument to the `action` method:
66 |
67 | return redirect()->action(
68 | 'UserController@profile', ['id' => 1]
69 | );
70 |
71 |
72 | ## Redirecting With Flashed Session Data
73 |
74 | Redirecting to a new URL and [flashing data to the session](/docs/{{version}}/session#flash-data) are usually done at the same time. Typically, this is done after successfully performing an action when you flash a success message to the session. For convenience, you may create a `RedirectResponse` instance and flash data to the session in a single, fluent method chain:
75 |
76 | Route::post('user/profile', function () {
77 | // Update the user's profile...
78 |
79 | return redirect('dashboard')->with('status', 'Profile updated!');
80 | });
81 |
82 | After the user is redirected, you may display the flashed message from the [session](/docs/{{version}}/session). For example, using [Blade syntax](/docs/{{version}}/blade):
83 |
84 | @if (session('status'))
85 |
86 | {{ session('status') }}
87 |
88 | @endif
89 |
--------------------------------------------------------------------------------
/redis.md:
--------------------------------------------------------------------------------
1 | # Redis
2 |
3 | - [Introduction](#introduction)
4 | - [Configuration](#configuration)
5 | - [Interacting With Redis](#interacting-with-redis)
6 | - [Pipelining Commands](#pipelining-commands)
7 | - [Pub / Sub](#pubsub)
8 |
9 |
10 | ## Introduction
11 |
12 | [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 via Composer:
13 |
14 | composer require predis/predis
15 |
16 |
17 | ### Configuration
18 |
19 | 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 utilized by your application:
20 |
21 | 'redis' => [
22 |
23 | 'cluster' => false,
24 |
25 | 'default' => [
26 | 'host' => '127.0.0.1',
27 | 'port' => 6379,
28 | 'database' => 0,
29 | ],
30 |
31 | ],
32 |
33 | The default server configuration should suffice for development. However, you are free to modify this array based on your environment. Each Redis server defined in your configuration file is required to have a name, host, and port.
34 |
35 | The `cluster` option will instruct 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.
36 |
37 | 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).
38 |
39 | If your Redis server requires authentication, you may supply a password by adding a `password` configuration item to your Redis server configuration array.
40 |
41 | > {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.
42 |
43 |
44 | ## Interacting With Redis
45 |
46 | You may interact with Redis by calling various methods on the `Redis` [facade](/docs/{{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 Redis `GET` command by calling the `get` method on the `Redis` facade:
47 |
48 | $user]);
68 | }
69 | }
70 |
71 | 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:
72 |
73 | Redis::set('name', 'Taylor');
74 |
75 | $values = Redis::lrange('names', 5, 10);
76 |
77 | 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:
78 |
79 | $values = Redis::command('lrange', ['name', 5, 10]);
80 |
81 | #### Using Multiple Redis Connections
82 |
83 | You may get a Redis instance by calling the `Redis::connection` method:
84 |
85 | $redis = Redis::connection();
86 |
87 | 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:
88 |
89 | $redis = Redis::connection('other');
90 |
91 |
92 | ### Pipelining Commands
93 |
94 | 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:
95 |
96 | Redis::pipeline(function ($pipe) {
97 | for ($i = 0; $i < 1000; $i++) {
98 | $pipe->set("key:$i", $i);
99 | }
100 | });
101 |
102 |
103 | ## Pub / Sub
104 |
105 | Laravel 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 and processes.
106 |
107 | First, let's setup a channel listener using the `subscribe` method. We'll place this method call within an [Artisan command](/docs/{{version}}/artisan) since calling the `subscribe` method begins a long-running process:
108 |
109 | 'bar']));
151 | });
152 |
153 | #### Wildcard Subscriptions
154 |
155 | Using the `psubscribe` method, you may subscribe to a wildcard channel, which may be useful for catching all messages on all channels. The `$channel` name will be passed as the second argument to the provided callback `Closure`:
156 |
157 | Redis::psubscribe(['*'], function($message, $channel) {
158 | echo $message;
159 | });
160 |
161 | Redis::psubscribe(['users.*'], function($message, $channel) {
162 | echo $message;
163 | });
164 |
--------------------------------------------------------------------------------
/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, you may have generated a Cron entry for each task you needed to schedule on your server. However, this can quickly become a pain, because your task schedule is no longer in source control and you must SSH into your server to add additional Cron entries.
14 |
15 | Laravel's command scheduler allows you to fluently and expressively define your command schedule within Laravel itself. When using the scheduler, only a single Cron entry is needed on your server. Your task schedule is defined in the `app/Console/Kernel.php` file's `schedule` method. To help you get started, a simple example is defined within the method.
16 |
17 | ### Starting The Scheduler
18 |
19 | When using the scheduler, you only need to add the following Cron entry to your server. If you do not know how to add Cron entries to your server, consider using a service such as [Laravel Forge](https://forge.laravel.com) which can manage the Cron entries for you:
20 |
21 | * * * * * php /path/to/artisan schedule:run >> /dev/null 2>&1
22 |
23 | This Cron will call the Laravel command scheduler every minute. When the `schedule:run` command is executed, Laravel will evaluate 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](/docs/{{version}}/artisan) and operating system commands. For example, you may use the `command` method to schedule an Artisan command using either the command's name or class:
64 |
65 | $schedule->command('emails:send --force')->daily();
66 |
67 | $schedule->command(EmailsCommand::class, ['--force'])->daily();
68 |
69 | The `exec` command may be used to issue a command to the operating system:
70 |
71 | $schedule->exec('node /home/forge/script.js')->daily();
72 |
73 |
74 | ### Schedule Frequency Options
75 |
76 | Of course, there are a variety of schedules you may assign to your task:
77 |
78 | Method | Description
79 | ------------- | -------------
80 | `->cron('* * * * * *');` | Run the task on a custom Cron schedule
81 | `->everyMinute();` | Run the task every minute
82 | `->everyFiveMinutes();` | Run the task every five minutes
83 | `->everyTenMinutes();` | Run the task every ten minutes
84 | `->everyThirtyMinutes();` | Run the task every thirty minutes
85 | `->hourly();` | Run the task every hour
86 | `->daily();` | Run the task every day at midnight
87 | `->dailyAt('13:00');` | Run the task every day at 13:00
88 | `->twiceDaily(1, 13);` | Run the task daily at 1:00 & 13:00
89 | `->weekly();` | Run the task every week
90 | `->monthly();` | Run the task every month
91 | `->monthlyOn(4, '15:00');` | Run the task every month on the 4th at 15:00
92 | `->quarterly();` | Run the task every quarter
93 | `->yearly();` | Run the task every year
94 | `->timezone('America/New_York');` | Set the timezone
95 |
96 | 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:
97 |
98 | // Run once per week on Monday at 1 PM...
99 | $schedule->call(function () {
100 | //
101 | })->weekly()->mondays()->at('13:00');
102 |
103 | // Run hourly from 8 AM to 5 PM on weekdays...
104 | $schedule->command('foo')
105 | ->weekdays()
106 | ->hourly()
107 | ->timezone('America/Chicago')
108 | ->between('8:00', '17:00');
109 |
110 | Below is a list of the additional schedule constraints:
111 |
112 | Method | Description
113 | ------------- | -------------
114 | `->weekdays();` | Limit the task to weekdays
115 | `->sundays();` | Limit the task to Sunday
116 | `->mondays();` | Limit the task to Monday
117 | `->tuesdays();` | Limit the task to Tuesday
118 | `->wednesdays();` | Limit the task to Wednesday
119 | `->thursdays();` | Limit the task to Thursday
120 | `->fridays();` | Limit the task to Friday
121 | `->saturdays();` | Limit the task to Saturday
122 | `->between($start, $end);` | Limit the task to run between start and end times
123 | `->when(Closure);` | Limit the task based on a truth test
124 |
125 | #### Between Time Constraints
126 |
127 | The `between` method may be used to limit the execution of a task based on the time of day:
128 |
129 | $schedule->command('reminders:send')
130 | ->hourly()
131 | ->between('7:00', '22:00');
132 |
133 | Similarly, the `unlessBetween` method can be used to exclude the execution of a task for a period of time:
134 |
135 | $schedule->command('reminders:send')
136 | ->hourly()
137 | ->unlessBetween('23:00', '4:00');
138 |
139 | #### Truth Test Constraints
140 |
141 | 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` returns `true`, the task will execute as long as no other constraining conditions prevent the task from running:
142 |
143 | $schedule->command('emails:send')->daily()->when(function () {
144 | return true;
145 | });
146 |
147 | The `skip` method may be seen as the inverse of `when`. If the `skip` method returns `true`, the scheduled task will not be executed:
148 |
149 | $schedule->command('emails:send')->daily()->skip(function () {
150 | return true;
151 | });
152 |
153 | When using chained `when` methods, the scheduled command will only execute if all `when` conditions return `true`.
154 |
155 |
156 | ### Preventing Task Overlaps
157 |
158 | 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:
159 |
160 | $schedule->command('emails:send')->withoutOverlapping();
161 |
162 | In this example, the `emails:send` [Artisan command](/docs/{{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.
163 |
164 |
165 | ## Task Output
166 |
167 | 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:
168 |
169 | $schedule->command('emails:send')
170 | ->daily()
171 | ->sendOutputTo($filePath);
172 |
173 | If you would like to append the output to a given file, you may use the `appendOutputTo` method:
174 |
175 | $schedule->command('emails:send')
176 | ->daily()
177 | ->appendOutputTo($filePath);
178 |
179 | 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. Before e-mailing the output of a task, you should configure Laravel's [e-mail services](/docs/{{version}}/mail):
180 |
181 | $schedule->command('foo')
182 | ->daily()
183 | ->sendOutputTo($filePath)
184 | ->emailOutputTo('foo@example.com');
185 |
186 | > {note} The `emailOutputTo`, `sendOutputTo` and `appendOutputTo` methods are exclusive to the `command` method and are not supported for `call`.
187 |
188 |
189 | ## Task Hooks
190 |
191 | Using the `before` and `after` methods, you may specify code to be executed before and after the scheduled task is complete:
192 |
193 | $schedule->command('emails:send')
194 | ->daily()
195 | ->before(function () {
196 | // Task is about to start...
197 | })
198 | ->after(function () {
199 | // Task is complete...
200 | });
201 |
202 | #### Pinging URLs
203 |
204 | 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 has finished execution:
205 |
206 | $schedule->command('emails:send')
207 | ->daily()
208 | ->pingBefore($url)
209 | ->thenPing($url);
210 |
211 | Using either the `pingBefore($url)` or `thenPing($url)` feature requires the Guzzle HTTP library. You can add Guzzle to your project using the Composer package manager:
212 |
213 | composer require guzzlehttp/guzzle
214 |
--------------------------------------------------------------------------------
/schema.md:
--------------------------------------------------------------------------------
1 | # Schema Builder
2 |
3 | - [Introduction](#introduction)
4 | - [Creating & Dropping Tables](#creating-and-dropping-tables)
5 | - [Adding Columns](#adding-columns)
6 | - [Changing Columns](#changing-columns)
7 | - [Renaming Columns](#renaming-columns)
8 | - [Dropping Columns](#dropping-columns)
9 | - [Checking Existence](#checking-existence)
10 | - [Adding Indexes](#adding-indexes)
11 | - [Foreign Keys](#foreign-keys)
12 | - [Dropping Indexes](#dropping-indexes)
13 | - [Dropping Timestamps & Soft Deletes](#dropping-timestamps)
14 | - [Storage Engines](#storage-engines)
15 |
16 |
17 | ## Introduction
18 |
19 | The Laravel `Schema` class provides a database agnostic way of manipulating tables. It works well with all of the databases supported by Laravel, and has a unified API across all of these systems.
20 |
21 |
22 | ## Creating & Dropping Tables
23 |
24 | To create a new database table, the `Schema::create` method is used:
25 |
26 | Schema::create('users', function($table)
27 | {
28 | $table->increments('id');
29 | });
30 |
31 | The first argument passed to the `create` method is the name of the table, and the second is a `Closure` which will receive a `Blueprint` object which may be used to define the new table.
32 |
33 | To rename an existing database table, the `rename` method may be used:
34 |
35 | Schema::rename($from, $to);
36 |
37 | To specify which connection the schema operation should take place on, use the `Schema::connection` method:
38 |
39 | Schema::connection('foo')->create('users', function($table)
40 | {
41 | $table->increments('id');
42 | });
43 |
44 | To drop a table, you may use the `Schema::drop` method:
45 |
46 | Schema::drop('users');
47 |
48 | Schema::dropIfExists('users');
49 |
50 |
51 | ## Adding Columns
52 |
53 | To update an existing table, we will use the `Schema::table` method:
54 |
55 | Schema::table('users', function($table)
56 | {
57 | $table->string('email');
58 | });
59 |
60 | The table builder contains a variety of column types that you may use when building your tables:
61 |
62 | Command | Description
63 | ------------- | -------------
64 | `$table->bigIncrements('id');` | Incrementing ID using a "big integer" equivalent.
65 | `$table->bigInteger('votes');` | BIGINT equivalent to the table
66 | `$table->binary('data');` | BLOB equivalent to the table
67 | `$table->boolean('confirmed');` | BOOLEAN equivalent to the table
68 | `$table->char('name', 4);` | CHAR equivalent with a length
69 | `$table->date('created_at');` | DATE equivalent to the table
70 | `$table->dateTime('created_at');` | DATETIME equivalent to the table
71 | `$table->decimal('amount', 5, 2);` | DECIMAL equivalent with a precision and scale
72 | `$table->double('column', 15, 8);` | DOUBLE equivalent with precision, 15 digits in total and 8 after the decimal point
73 | `$table->enum('choices', array('foo', 'bar'));` | ENUM equivalent to the table
74 | `$table->float('amount');` | FLOAT equivalent to the table
75 | `$table->increments('id');` | Incrementing ID to the table (primary key).
76 | `$table->integer('votes');` | INTEGER equivalent to the table
77 | `$table->json('options');` | JSON equivalent to the table
78 | `$table->longText('description');` | LONGTEXT equivalent to the table
79 | `$table->mediumInteger('numbers');` | MEDIUMINT equivalent to the table
80 | `$table->mediumText('description');` | MEDIUMTEXT equivalent to the table
81 | `$table->morphs('taggable');` | Adds INTEGER `taggable_id` and STRING `taggable_type`
82 | `$table->nullableTimestamps();` | Same as `timestamps()`, except allows NULLs
83 | `$table->smallInteger('votes');` | SMALLINT equivalent to the table
84 | `$table->tinyInteger('numbers');` | TINYINT equivalent to the table
85 | `$table->softDeletes();` | Adds **deleted\_at** column for soft deletes
86 | `$table->string('email');` | VARCHAR equivalent column
87 | `$table->string('name', 100);` | VARCHAR equivalent with a length
88 | `$table->text('description');` | TEXT equivalent to the table
89 | `$table->time('sunrise');` | TIME equivalent to the table
90 | `$table->timestamp('added_on');` | TIMESTAMP equivalent to the table
91 | `$table->timestamps();` | Adds **created\_at** and **updated\_at** columns
92 | `$table->rememberToken();` | Adds `remember_token` as VARCHAR(100) NULL
93 | `->nullable()` | Designate that the column allows NULL values
94 | `->default($value)` | Declare a default value for a column
95 | `->unsigned()` | Set INTEGER to UNSIGNED
96 |
97 | #### Using After On MySQL
98 |
99 | If you are using the MySQL database, you may use the `after` method to specify the order of columns:
100 |
101 | $table->string('name')->after('email');
102 |
103 |
104 | ## Changing Columns
105 |
106 | Sometimes you may need to modify an existing column. For example, you may wish to increase the size of a string column. The `change` method makes it easy! For example, let's increase the size of the `name` column from 25 to 50:
107 |
108 | Schema::table('users', function($table)
109 | {
110 | $table->string('name', 50)->change();
111 | });
112 |
113 | We could also modify a column to be nullable:
114 |
115 | Schema::table('users', function($table)
116 | {
117 | $table->string('name', 50)->nullable()->change();
118 | });
119 |
120 |
121 | ## Renaming Columns
122 |
123 | To rename a column, you may use the `renameColumn` method on the Schema builder. Before renaming a column, be sure to add the `doctrine/dbal` dependency to your `composer.json` file.
124 |
125 | Schema::table('users', function($table)
126 | {
127 | $table->renameColumn('from', 'to');
128 | });
129 |
130 | > **Note:** Renaming `enum` column types is not supported.
131 |
132 |
133 | ## Dropping Columns
134 |
135 | To drop a column, you may use the `dropColumn` method on the Schema builder. Before dropping a column, be sure to add the `doctrine/dbal` dependency to your `composer.json` file.
136 |
137 | #### Dropping A Column From A Database Table
138 |
139 | Schema::table('users', function($table)
140 | {
141 | $table->dropColumn('votes');
142 | });
143 |
144 | #### Dropping Multiple Columns From A Database Table
145 |
146 | Schema::table('users', function($table)
147 | {
148 | $table->dropColumn(array('votes', 'avatar', 'location'));
149 | });
150 |
151 |
152 | ## Checking Existence
153 |
154 | #### Checking For Existence Of Table
155 |
156 | You may easily check for the existence of a table or column using the `hasTable` and `hasColumn` methods:
157 |
158 | if (Schema::hasTable('users'))
159 | {
160 | //
161 | }
162 |
163 | #### Checking For Existence Of Columns
164 |
165 | if (Schema::hasColumn('users', 'email'))
166 | {
167 | //
168 | }
169 |
170 |
171 | ## Adding Indexes
172 |
173 | The schema builder supports several types of indexes. There are two ways to add them. First, you may fluently define them on a column definition, or you may add them separately:
174 |
175 | $table->string('email')->unique();
176 |
177 | Or, you may choose to add the indexes on separate lines. Below is a list of all available index types:
178 |
179 | Command | Description
180 | ------------- | -------------
181 | `$table->primary('id');` | Adding a primary key
182 | `$table->primary(array('first', 'last'));` | Adding composite keys
183 | `$table->unique('email');` | Adding a unique index
184 | `$table->index('state');` | Adding a basic index
185 |
186 |
187 | ## Foreign Keys
188 |
189 | Laravel also provides support for adding foreign key constraints to your tables:
190 |
191 | $table->integer('user_id')->unsigned();
192 | $table->foreign('user_id')->references('id')->on('users');
193 |
194 | In this example, we are stating that the `user_id` column references the `id` column on the `users` table. Make sure to create the foreign key column first!
195 |
196 | You may also specify options for the "on delete" and "on update" actions of the constraint:
197 |
198 | $table->foreign('user_id')
199 | ->references('id')->on('users')
200 | ->onDelete('cascade');
201 |
202 | To drop a foreign key, you may use the `dropForeign` method. A similar naming convention is used for foreign keys as is used for other indexes:
203 |
204 | $table->dropForeign('posts_user_id_foreign');
205 |
206 | > **Note:** When creating a foreign key that references an incrementing integer, remember to always make the foreign key column `unsigned`.
207 |
208 |
209 | ## Dropping Indexes
210 |
211 | To drop an index you must specify the index's name. Laravel assigns a reasonable name to the indexes by default. Simply concatenate the table name, the names of the column in the index, and the index type. Here are some examples:
212 |
213 | Command | Description
214 | ------------- | -------------
215 | `$table->dropPrimary('users_id_primary');` | Dropping a primary key from the "users" table
216 | `$table->dropUnique('users_email_unique');` | Dropping a unique index from the "users" table
217 | `$table->dropIndex('geo_state_index');` | Dropping a basic index from the "geo" table
218 |
219 |
220 | ## Dropping Timestamps & SoftDeletes
221 |
222 | To drop the `timestamps`, `nullableTimestamps` or `softDeletes` column types, you may use the following methods:
223 |
224 | Command | Description
225 | ------------- | -------------
226 | `$table->dropTimestamps();` | Dropping the **created\_at** and **updated\_at** columns from the table
227 | `$table->dropSoftDeletes();` | Dropping **deleted\_at** column from the table
228 |
229 |
230 | ## Storage Engines
231 |
232 | To set the storage engine for a table, set the `engine` property on the schema builder:
233 |
234 | Schema::create('users', function($table)
235 | {
236 | $table->engine = 'InnoDB';
237 |
238 | $table->string('email');
239 | });
240 |
--------------------------------------------------------------------------------
/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 the `database/seeds` directory. 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, execute the `make:seeder` [Artisan command](/docs/{{version}}/artisan). All seeders generated by the framework will be placed in the `database/seeds` 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](/docs/{{version}}/artisan) is executed. Within the `run` method, you may insert data into your database however you wish. You may use the [query builder](/docs/{{version}}/queries) to manually insert data or you may use [Eloquent model factories](/docs/{{version}}/database-testing#writing-factories).
22 |
23 | As an example, let's modify the default `DatabaseSeeder` class and 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](/docs/{{version}}/database-testing#writing-factories) to conveniently generate large amounts of database records. First, review the [model factory documentation](/docs/{{version}}/database-testing#writing-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 | $this->call(UsersTableSeeder::class);
79 | $this->call(PostsTableSeeder::class);
80 | $this->call(CommentsTableSeeder::class);
81 | }
82 |
83 |
84 | ## Running Seeders
85 |
86 | 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:
87 |
88 | php artisan db:seed
89 |
90 | php artisan db:seed --class=UsersTableSeeder
91 |
92 | 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:
93 |
94 | php artisan migrate:refresh --seed
95 |
--------------------------------------------------------------------------------
/ssh.md:
--------------------------------------------------------------------------------
1 | # SSH
2 |
3 | - [Yapılandırma](#configuration)
4 | - [Temel Kullanım](#basic-usage)
5 | - [Görevler](#tasks)
6 | - [SFTP Dosya İndirmeleri](#sftp-downloads)
7 | - [SFTP Dosya Göndermeleri](#sftp-uploads)
8 | - [Uzak Günlüklerin İzlenmesi](#tailing-remote-logs)
9 | - [Envoy Görev Çalıştırıcısı](#envoy-task-runner)
10 |
11 |
12 | ## Yapılandırma
13 |
14 | Laravel uzak sunuculara SSH (Secure Shell) iletişimi ve komutlar çalıştırmak için basit bir yol içerir ve uzak sunucularda çalışan Artisan görevlerini kolayca inşa etmenize imkan verir. `SSH` facade'ı uzak sunucularınıza bağlanmanız ve komutlar çalıştırmanız için erişim noktası sağlar.
15 |
16 | Yapılandırma dosyası `config/remote.php` konumundadır ve uzak bağlantılarınızı yapılandırmak için gerekli tüm seçenekleri içerir. Bu dosyadaki `connections` dizisi, sürücülerinizin isimlerine göre anahtarlanmış bir listesini taşır. Bu `connections` dizisindeki erişim güven bilgilerini (credentials) doldurduktan sonra uzak görevleri çalıştırmaya hazır olacaksınız. Unutmayın, `SSH`, ya bir password ya da bir SSH key kullanarak kimlik doğrulaması yapabilmektedir.
17 |
18 | > **Not:** Uzak sunucunuzda çeşitli görevleri kolayca çalıştırma ihtiyacınız mı var? [Envoy görev çalıştırıcısına](#envoy-task-runner) bir bakın!
19 |
20 |
21 | ## Temel Kullanım
22 |
23 | #### Komutları Default Sunucuda Çalıştırmak
24 |
25 | Komutlarınızı `default` uzak bağlantınızda çalıştırmak için `SSH::run` metodunu kullanın:
26 |
27 | SSH::run(array(
28 | 'cd /var/www',
29 | 'git pull origin master',
30 | ));
31 |
32 | #### Komutları Belirli Bir Bağlantıda Çalıştırmak
33 |
34 | Alternatif olarak, `into` metodunu kullanmak suretiyle komutları belirli bir bağlantı üzerinde çalıştırabilirsiniz:
35 |
36 | SSH::into('staging')->run(array(
37 | 'cd /var/www',
38 | 'git pull origin master',
39 | ));
40 |
41 | #### Komut Çıktılarını Yakalamak
42 |
43 | `run` metoduna bir Closure geçmek suretiyle, uzak komutlarınızın "canlı" çıktısını yakalayabilirsiniz:
44 |
45 | SSH::run($commands, function($line)
46 | {
47 | echo $line.PHP_EOL;
48 | });
49 |
50 | ## Görevler
51 |
52 |
53 | Eğer her zaman birlikte çalışması gereken bir grup komut tanımlamanız gerekiyorsa, bir `task`(görev) tanımlamak için `define` metodunu kullanabilirsiniz:
54 |
55 | SSH::into('staging')->define('deploy', array(
56 | 'cd /var/www',
57 | 'git pull origin master',
58 | 'php artisan migrate',
59 | ));
60 |
61 | Bu şekilde bir task tanımladıktan sonra, onu çalıştırmak için `task` metodunu kullanabilirsiniz:
62 |
63 | SSH::into('staging')->task('deploy', function($line)
64 | {
65 | echo $line.PHP_EOL;
66 | });
67 |
68 |
69 | ## SFTP Dosya İndirmeleri
70 |
71 | `SSH` sınıfı `get` ve `getString` metodları kullanılarak, dosyalar indirmek için basit bir yol sağlar:
72 |
73 | SSH::into('staging')->get($remotePath, $localPath);
74 |
75 | $contents = SSH::into('staging')->getString($remotePath);
76 |
77 |
78 | ## SFTP Dosya Göndermeleri
79 |
80 | `SSH` sınıfı aynı zamanda `put` ve `putString` metodları kullanılarak sunucuya dosyalar, hatta stringler upload etmek için de basit bir yol içerir:
81 |
82 | SSH::into('staging')->put($localFile, $remotePath);
83 |
84 | SSH::into('staging')->putString($remotePath, 'Foo');
85 |
86 |
87 | ## Uzak Günlüklerin İzlenmesi
88 |
89 | Laravel sizin uzak bağlantılarınızın herhangi birindeki `laravel.log` dosyalarının izlenmesi için yararlı bir komut içermektedir. Bunun için basitçe `tail` Artisan komutunu kullanın ve izlemek istediğiniz uzak bağlantının adını belirtin:
90 |
91 | php artisan tail staging
92 |
93 | php artisan tail staging --path=/path/to/log.file
94 |
95 |
96 | ## Envoy Görev Çalıştırıcısı
97 |
98 | - [Yükleme](#envoy-installation)
99 | - [Görevlerin Çalıştırılması](#envoy-running-tasks)
100 | - [Birden Çok Sunucu](#envoy-multiple-servers)
101 | - [Paralel Çalıştırma](#envoy-parallel-execution)
102 | - [Task Makroları](#envoy-task-macros)
103 | - [Bildirimler](#envoy-notifications)
104 | - [Envoy'in Güncellenmesi](#envoy-updating-envoy)
105 |
106 | Laravel Envoy, uzak sunucularınızda ortak görevler tanımlanması için temiz, minimal bir sözdizimi sağlar. [Blade](/docs/templates#blade-templating) tarzı bir sözdizimi kullanarak yayımlama, Artisan komutları ve başka şeyler için kolayca görevler inşa edebilirsiniz.
107 |
108 | > **Note:** Envoy, PHP versiyon 5.4 veya daha üstünü gerektirir ve sadece Mac / Linux işletim sistemlerinde çalışır.
109 |
110 |
111 | ### Yükleme
112 |
113 | Önce, Composer `global` komutunu kullanarak Envoy'u yükleyin:
114 |
115 | composer global require "laravel/envoy=~1.0"
116 |
117 | Terminalinizde `envoy` komutunu çalıştırdığınız zaman `envoy` çalıştırılabilir dosyasının bulunabilmesi için PATH ayarınızda `~/.composer/vendor/bin` dizininin yer aldığından emin olun.
118 |
119 | Sonra da, projenizin kökünde bir `Envoy.blade.php` dosyası oluşturun. İşte başlayabileceğiniz bir örnek:
120 |
121 | @servers(['web' => '192.168.1.1'])
122 |
123 | @task('foo', ['on' => 'web'])
124 | ls -la
125 | @endtask
126 |
127 | Görebileceğiniz gibi, dosyanın en üstünde bir `@servers` dizisi tanımlanır. Bu sunucuları, task (görev) deklarasyonlarınızın `on` seçeneğinde refere edebilirsiniz. Bu `@task` deklarasyonlarınızın içerisine, task çalıştırıldığı zaman sunucunuzda çalıştırılacak olan Bash kodunu koyacaksınız.
128 |
129 | Bir iskelet Envoy dosyasını kolayca oluşturmak için `init` komutu kullanılabilir:
130 |
131 | envoy init user@192.168.1.1
132 |
133 |
134 | ### Görevlerin Çalıştırılması
135 |
136 | Bir görevi çalıştırmak için Envoy yüklemenizin `run` komutunu kullanın:
137 |
138 | envoy run foo
139 |
140 | Eğer gerekliyse, komut satırı seçeneklerini kullanarak Envoy dosyasına değişkenler geçebilirsiniz:
141 |
142 | envoy run deploy --branch=master
143 |
144 | Bu seçenekleri, kullandığınız Blade sözdizimi aracılığıyla kullanabilirsiniz:
145 |
146 | @servers(['web' => '192.168.1.1'])
147 |
148 | @task('deploy', ['on' => 'web'])
149 | cd site
150 | git pull origin {{ $branch }}
151 | php artisan migrate
152 | @endtask
153 |
154 | #### Bootstrapping
155 |
156 | Envoy dosyasının içinde değişkenler deklare etmek ve genel PHP işi yapmak için ```@setup``` direktifini kullanabilirsiniz:
157 |
158 | @setup
159 | $now = new DateTime();
160 |
161 | $environment = isset($env) ? $env : "testing";
162 | @endsetup
163 |
164 | Ayrıca bir PHP dosyası ```@include`` etmek için @include kullanabilirsiniz:
165 |
166 | @include('vendor/autoload.php');
167 |
168 |
169 | ### Birden Çok Sunucu
170 |
171 | Bir görevi birden çok sunucuda kolaylıkla çalıştırabilirsiniz. Sadece task deklarasyonunda sunucuları listeleyin:
172 |
173 | @servers(['web-1' => '192.168.1.1', 'web-2' => '192.168.1.2'])
174 |
175 | @task('deploy', ['on' => ['web-1', 'web-2']])
176 | cd site
177 | git pull origin {{ $branch }}
178 | php artisan migrate
179 | @endtask
180 |
181 | Ön tanımlı olarak, ilgili görev her bir sunucuda seri olarak çalıştırılacaktır. Yani, görev bir sonraki sunucuda çalışmaya başlamadan önce, önceki çalışmasını tamamlayacaktır.
182 |
183 |
184 | ### Paralel Çalıştırma
185 |
186 | Eğer bir görevi birden çok sunucuda paralel olarak çalıştırmak istiyorsanız, yapmanız gereken tek şey task deklarasyonunuza `parallel` seçeneğini eklemektir:
187 |
188 | @servers(['web-1' => '192.168.1.1', 'web-2' => '192.168.1.2'])
189 |
190 | @task('deploy', ['on' => ['web-1', 'web-2'], 'parallel' => true])
191 | cd site
192 | git pull origin {{ $branch }}
193 | php artisan migrate
194 | @endtask
195 |
196 |
197 | ### Task Makroları
198 |
199 | Makrolar basit bir komut kullanarak sıralı bir biçimde çalışacak bir görev kümesi tanımlamanıza imkan verirler. Örneğin:
200 |
201 | @servers(['web' => '192.168.1.1'])
202 |
203 | @macro('deploy')
204 | foo
205 | bar
206 | @endmacro
207 |
208 | @task('foo')
209 | echo "HELLO"
210 | @endtask
211 |
212 | @task('bar')
213 | echo "WORLD"
214 | @endtask
215 |
216 | Artık bu `deploy` makrosu tek, basit bir komut aracılığı ile çalıştırılabilecektir:
217 |
218 | envoy run deploy
219 |
220 |
221 |
222 | ### Bildirimler
223 |
224 | #### HipChat
225 |
226 | Bir görevi çalıştırdıktan sonra, basit `@hipchat` direktifini kullanarak ekibinizin HipChat odasına bir bildirim gönderebilirsiniz:
227 |
228 | @servers(['web' => '192.168.1.1'])
229 |
230 | @task('foo', ['on' => 'web'])
231 | ls -la
232 | @endtask
233 |
234 | @after
235 | @hipchat('token', 'room', 'Envoy')
236 | @endafter
237 |
238 | Ayrıca hipchat odasına, özel bir mesaj da belirtebilirsiniz. ```@setup``` içinde deklare edilen veya ```@include``` ile dahil edilen her değişkenin mesajda kullanılması mümkündür:
239 |
240 | @after
241 | @hipchat('token', 'room', 'Envoy', "$task ran on [$environment]")
242 | @endafter
243 |
244 | Bu, ekibinizi sunucu üzerinde çalıştırılan görevler hakkında haberdar tutmak için inanılmaz basit bir yoludur.
245 |
246 | #### Slack
247 |
248 | [Slack](https://slack.com)'a bir bildirim göndermek için aşağıdaki sözdizimi kullanılabilir:
249 |
250 | @after
251 | @slack('team', 'token', 'channel')
252 | @endafter
253 |
254 |
255 | ### Envoy'un Güncellenmesi
256 |
257 | Envoy'u güncellemek için, tek yapacağınız `self-update`komutunu çalıştırmaktır:
258 |
259 | envoy self-update
260 |
261 | Eğer Envoy yüklediğiniz yer `/usr/local/bin` ise, `sudo` kullanmanız gerekebilir:
262 |
263 | composer global update
264 |
--------------------------------------------------------------------------------
/templates.md:
--------------------------------------------------------------------------------
1 | # Templates
2 |
3 | - [Blade Templating](#blade-templating)
4 | - [Other Blade Control Structures](#other-blade-control-structures)
5 | - [Extending Blade](#extending-blade)
6 |
7 |
8 | ## Blade Templating
9 |
10 | Blade is a simple, yet powerful templating engine provided with Laravel. Unlike controller layouts, Blade is driven by _template inheritance_ and _sections_. All Blade templates should use the `.blade.php` extension.
11 |
12 | #### Defining A Blade Layout
13 |
14 |
15 |
16 |
17 |
18 | @section('sidebar')
19 | This is the master sidebar.
20 | @stop
21 |
22 |
40 | @stop
41 |
42 | Note that views which `extend` a Blade layout simply override sections from the layout. Content of the layout can be included in a child view using the `@parent` directive in a section, allowing you to append to the contents of a layout section such as a sidebar or footer.
43 |
44 | Sometimes, such as when you are not sure if a section has been defined, you may wish to pass a default value to the `@yield` directive. You may pass the default value as the second argument:
45 |
46 | @yield('section', 'Default Content')
47 |
48 |
49 | ## Other Blade Control Structures
50 |
51 | #### Echoing Data
52 |
53 | Hello, {{ $name }}.
54 |
55 | The current UNIX timestamp is {{ time() }}.
56 |
57 | #### Echoing Data After Checking For Existence
58 |
59 | Sometimes you may wish to echo a variable, but you aren't sure if the variable has been set. Basically, you want to do this:
60 |
61 | {{ isset($name) ? $name : 'Default' }}
62 |
63 | However, instead of writing a ternary statement, Blade allows you to use the following convenient short-cut:
64 |
65 | {{ $name or 'Default' }}
66 |
67 | #### Displaying Raw Text With Curly Braces
68 |
69 | If you need to display a string that is wrapped in curly braces, you may escape the Blade behavior by prefixing your text with an `@` symbol:
70 |
71 | @{{ This will not be processed by Blade }}
72 |
73 | If you don't want the data to be escaped, you may use the following syntax:
74 |
75 | Hello, {!! $name !!}.
76 |
77 | > **Note:** Be very careful when echoing content that is supplied by users of your application. Always use the triple curly brace syntax to escape any HTML entities in the content.
78 |
79 | #### If Statements
80 |
81 | @if (count($records) === 1)
82 | I have one record!
83 | @elseif (count($records) > 1)
84 | I have multiple records!
85 | @else
86 | I don't have any records!
87 | @endif
88 |
89 | @unless (Auth::check())
90 | You are not signed in.
91 | @endunless
92 |
93 | #### Loops
94 |
95 | @for ($i = 0; $i < 10; $i++)
96 | The current value is {{ $i }}
97 | @endfor
98 |
99 | @foreach ($users as $user)
100 |
111 | @endwhile
112 |
113 | #### Including Sub-Views
114 |
115 | @include('view.name')
116 |
117 | You may also pass an array of data to the included view:
118 |
119 | @include('view.name', ['some' => 'data'])
120 |
121 | #### Overwriting Sections
122 |
123 | To overwrite a section entirely, you may use the `overwrite` statement:
124 |
125 | @extends('list.item.container')
126 |
127 | @section('list.item.content')
128 |
This is an item of type {{ $item->type }}
129 | @overwrite
130 |
131 | #### Displaying Language Lines
132 |
133 | @lang('language.line')
134 |
135 | @choice('language.line', 1)
136 |
137 | #### Comments
138 |
139 | {{-- This comment will not be in the rendered HTML --}}
140 |
141 |
142 | ## Extending Blade
143 |
144 | Blade even allows you to define your own custom control structures. When a Blade file is compiled, each custom extension is called with the view contents, allowing you to do anything from simple `str_replace` manipulations to more complex regular expressions.
145 |
146 | The Blade compiler comes with the helper methods `createMatcher` and `createPlainMatcher`, which generate the expression you need to build your own custom directives.
147 |
148 | The `createPlainMatcher` method is used for directives with no arguments like `@endif` and `@stop`, while `createMatcher` is used for directives with arguments.
149 |
150 | The following example creates a `@datetime($var)` directive which simply calls `->format()` on `$var`:
151 |
152 | Blade::extend(function($view, $compiler)
153 | {
154 | $pattern = $compiler->createMatcher('datetime');
155 |
156 | return preg_replace($pattern, '$1format(\'m/d/Y H:i\'); ?>', $view);
157 | });
158 |
--------------------------------------------------------------------------------
/testing.md:
--------------------------------------------------------------------------------
1 | # Testing
2 |
3 | - [Introduction](#introduction)
4 | - [Environment](#environment)
5 | - [Creating & Running Tests](#creating-and-running-tests)
6 |
7 |
8 | ## Introduction
9 |
10 | Laravel is built with testing in mind. In fact, support for testing with PHPUnit is included out of the box and a `phpunit.xml` file is already setup for your application. The framework also ships with convenient helper methods that allow you to expressively test your applications.
11 |
12 | An `ExampleTest.php` file is provided in the `tests` directory. After installing a new Laravel application, simply run `phpunit` on the command line to run your tests.
13 |
14 |
15 | ## Environment
16 |
17 | When running tests, Laravel will automatically set the configuration environment to `testing`. Laravel automatically configures the session and cache to the `array` driver while testing, meaning no session or cache data will be persisted while testing.
18 |
19 | You are free to define other testing environment configuration values as necessary. The `testing` environment variables may be configured in the `phpunit.xml` file, but make sure to clear your configuration cache using the `config:clear` Artisan command before running your tests!
20 |
21 |
22 | ## Creating & Running Tests
23 |
24 | To create a new test case, use the `make:test` Artisan command:
25 |
26 | php artisan make:test UserTest
27 |
28 | This command will place a new `UserTest` class within your `tests` directory. You may then define test methods as you normally would using PHPUnit. To run your tests, simply execute the `phpunit` command from your terminal:
29 |
30 | assertTrue(true);
46 | }
47 | }
48 |
49 | > {note} If you define your own `setUp` method within a test class, be sure to call `parent::setUp`.
50 |
--------------------------------------------------------------------------------
/views.md:
--------------------------------------------------------------------------------
1 | # Views
2 |
3 | - [Creating Views](#creating-views)
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 | ## Creating Views
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. A simple view might look something like this:
12 |
13 |
14 |
15 |
16 |
17 |
Hello, {{ $name }}
18 |
19 |
20 |
21 | Since this view is stored at `resources/views/greeting.blade.php`, we may return it using the global `view` helper like so:
22 |
23 | Route::get('/', function () {
24 | return view('greeting', ['name' => 'James']);
25 | });
26 |
27 | 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 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 using [Blade syntax](/docs/{{version}}/blade).
28 |
29 | 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.blade.php`, you may reference it like so:
30 |
31 | return view('admin.profile', $data);
32 |
33 | #### Determining If A View Exists
34 |
35 | If you need to determine if a view exists, you may use the `View` facade. The `exists` method will return `true` if the view exists:
36 |
37 | use Illuminate\Support\Facades\View;
38 |
39 | if (View::exists('emails.customer')) {
40 | //
41 | }
42 |
43 |
44 | ## Passing Data To Views
45 |
46 | As you saw in the previous examples, you may pass an array of data to views:
47 |
48 | return view('greetings', ['name' => 'Victoria']);
49 |
50 | 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:
51 |
52 | return view('greeting')->with('name', 'Victoria');
53 |
54 |
55 | #### Sharing Data With All Views
56 |
57 | 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 facade's `share` method. Typically, you should 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:
58 |
59 |
89 | ## View Composers
90 |
91 | 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.
92 |
93 | For this example, let's register the view composers within a [service provider](/docs/{{version}}/providers). We'll use the `View` facade 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:
94 |
95 | {note} 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.
134 |
135 | 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:
136 |
137 | users = $users;
163 | }
164 |
165 | /**
166 | * Bind data to the view.
167 | *
168 | * @param View $view
169 | * @return void
170 | */
171 | public function compose(View $view)
172 | {
173 | $view->with('count', $this->users->count());
174 | }
175 | }
176 |
177 | Just before the view is rendered, the composer's `compose` method is called with the `Illuminate\View\View` instance. You may use the `with` method to bind data to the view.
178 |
179 | > {tip} All view composers are resolved via the [service container](/docs/{{version}}/container), so you may type-hint any dependencies you need within a composer's constructor.
180 |
181 | #### Attaching A Composer To Multiple Views
182 |
183 | 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:
184 |
185 | View::composer(
186 | ['profile', 'dashboard'],
187 | 'App\Http\ViewComposers\MyViewComposer'
188 | );
189 |
190 | The `composer` method also accepts the `*` character as a wildcard, allowing you to attach a composer to all views:
191 |
192 | View::composer('*', function ($view) {
193 | //
194 | });
195 |
196 | #### View Creators
197 |
198 | View **creators** are very similar to view composers; however, they are executed immediately after the view is instantiated instead of waiting until the view is about to render. To register a view creator, use the `creator` method:
199 |
200 | View::creator('profile', 'App\Http\ViewCreators\ProfileCreator');
201 |
--------------------------------------------------------------------------------