├── artisan.md ├── authentication.md ├── billing.md ├── bus.md ├── cache.md ├── collections.md ├── commands.md ├── configuration.md ├── container.md ├── contracts.md ├── contributing.md ├── contributions.md ├── controllers.md ├── database.md ├── documentation.md ├── elixir.md ├── eloquent.md ├── encryption.md ├── envoy.md ├── errors.md ├── events.md ├── extending.md ├── facades.md ├── filesystem.md ├── hashing.md ├── helpers.md ├── homestead.md ├── installation.md ├── license.md ├── lifecycle.md ├── localization.md ├── mail.md ├── middleware.md ├── migrations.md ├── packages.md ├── pagination.md ├── providers.md ├── queries.md ├── queues.md ├── readme.md ├── redis.md ├── releases.md ├── requests.md ├── responses.md ├── routing.md ├── schema.md ├── session.md ├── structure.md ├── templates.md ├── testing.md ├── upgrade.md ├── validation.md └── views.md /artisan.md: -------------------------------------------------------------------------------- 1 | # Artisan CLI 2 | 3 | - [Introdução](#introduction) 4 | - [Uso](#usage) 5 | - [Chamando os Comandos de Fora do CLI](#calling-commands-outside-of-cli) 6 | - [Agendando Comandos Artisan](#scheduling-artisan-commands) 7 | 8 | 9 | ## Introdução 10 | 11 | Artisan é o nome da interface da linha de comando incluída no Laravel. Esta interface fornece um bom número de comandos auxiliares para que você use durante o desenvolvimento de sua aplicação. O artisan é impulsionado pelo poderoso componente de Console do Symfony framework. 12 | 13 | 14 | ## Uso 15 | 16 | #### Listando todos os comandos Disponíveis 17 | 18 | Para ver a lista de todos os comandos Artisan, você deve utilizar o comando `list`. 19 | 20 | php artisan list 21 | 22 | #### Visualizando a Tela de Ajuda para um Comando 23 | 24 | Todos os comandos também incluem uma tela de "help" que mostra e descreve os comandos e seus respectivos parâmetros e opções. Para ver a tela de "help" (ajuda), simplesmente preceda o nome do comando com `help`. 25 | 26 | php artisan help migrate 27 | 28 | #### Especificando O Ambiente de Configuração 29 | 30 | Você pode especificar o ambiente em que o comando é executando usando o prefixo `--env`: 31 | 32 | php artisan migrate --env=local 33 | 34 | #### Exibindo Sua Versão Atual do Laravel 35 | 36 | Você também pode ver a versão atual do instalação do seu Laravel utilizando a opção `--version`: 37 | 38 | php artisan --version 39 | 40 | 41 | ## Chamando os Comandos de Fora do CLI 42 | 43 | Algumas vezes você pode desejar executar o comando Artisan de fora do CLI. Por exemplo, vocẽ pode desejar executar o comando Artisan de uma rota HTTP. Apenas use a fachada `Artisan`: 44 | 45 | Route::get('/foo', function() 46 | { 47 | $exitCode = Artisan::call('command:name', ['--option' => 'foo']); 48 | 49 | // 50 | }); 51 | 52 | 53 | Você pode até enfileirar comandos Artisan para que eles sejam processados em segundo plano pelo seu [queue workers](/docs/{{version}}/queues): 54 | 55 | Route::get('/foo', function() 56 | { 57 | Artisan::queue('command:name', ['--option' => 'foo']); 58 | 59 | // 60 | }); 61 | 62 | 63 | ## Agendando Comandos Artisan 64 | 65 | No passado, desenvolvedores teêm gerado uma entrada de Cron para cada comando que eles queriam agendar. Contudo, isto é uma baita dor de cabeça. Seu console de agendamento não está mais no controle de origem, e você deve realizar uma conexão SSH com o seu servidor para dar entradas de Cron. Vamos fazer sua nossas vidas mais fáceis. O comando agendados do Laravel lhe permite nativamente definir seu comando agendador apenas com o próprio Laravel, e apenas uma entrada de Cron se faz necessária no seu servidor. 66 | 67 | Seu comando agendador é armazenado no arquivo `app/Console/Kernel.php`. Dentro desta classe você verá o método `schedule`. Para ajudar você a começar, um simples exemplo é incluído com o método. Sinta-se a vontade para adicionar quantas tarefas agendadas você desejar para o objeto `Schedule`. A única entrada de Cron que você precisa adicionar para o seu servidor é esta: 68 | 69 | * * * * * php /path/to/artisan schedule:run 1>> /dev/null 2>&1 70 | 71 | 72 | Este Cron(tarefa agendada) chamará o comando de agendamento do Laravel todo minuto. Em seguida, Laravel avalia sua tarefa agendada e executa os que são devidos. Não poderia ser mais fácil do que isto. 73 | 74 | ### Mais Exemplos de Agendamento 75 | 76 | Vamos dar uma olhada em mais alguns exemplos de agendamentos: 77 | 78 | #### Agendamentos com Closures 79 | 80 | $schedule->call(function() 81 | { 82 | // Do some task... 83 | 84 | })->hourly(); 85 | 86 | #### Comandos de Agendamento via Terminal 87 | 88 | $schedule->exec('composer self-update')->daily(); 89 | 90 | #### Expressão Manual de Cron 91 | 92 | $schedule->command('foo')->cron('* * * * *'); 93 | 94 | #### Tarefas Frequentes 95 | 96 | $schedule->command('foo')->everyFiveMinutes(); 97 | 98 | $schedule->command('foo')->everyTenMinutes(); 99 | 100 | $schedule->command('foo')->everyThirtyMinutes(); 101 | 102 | #### Tarefas Diárias 103 | 104 | $schedule->command('foo')->daily(); 105 | 106 | #### Tarefas Diárias em Um Horário Específico (24 Horas) 107 | 108 | $schedule->command('foo')->dailyAt('15:00'); 109 | 110 | #### Tarefas Realizadas Duas Vezes ao Dia 111 | 112 | $schedule->command('foo')->twiceDaily(); 113 | 114 | #### Tarefas Executadas Todos os Dias da Semana 115 | 116 | $schedule->command('foo')->weekdays(); 117 | 118 | #### Tarefas Realizadas em um Dia da Semana em Específico 119 | 120 | $schedule->command('foo')->weekly(); 121 | 122 | // Schedule weekly job for specific day (0-6) and time... 123 | $schedule->command('foo')->weeklyOn(1, '8:00'); 124 | 125 | #### Tarefas Mensais 126 | 127 | $schedule->command('foo')->monthly(); 128 | 129 | #### Tarefas que são executadas em dias específicos da semana 130 | 131 | $schedule->command('foo')->mondays(); 132 | $schedule->command('foo')->tuesdays(); 133 | $schedule->command('foo')->wednesdays(); 134 | $schedule->command('foo')->thursdays(); 135 | $schedule->command('foo')->fridays(); 136 | $schedule->command('foo')->saturdays(); 137 | $schedule->command('foo')->sundays(); 138 | 139 | #### Previnindo que tarefas de Prevent Jobs From Overlapping 140 | 141 | Por padrão, tarefas agendadas serão executadas até mesmo que a instância anterior da tarefa ainda estiver sendo executada. Para que isto não ocorra, você pode usar o método withoutOverlapping`: 142 | 143 | $schedule->command('foo')->withoutOverlapping(); 144 | 145 | In this example, the `foo` command will be run every minute if it is not already running. 146 | 147 | #### Limitando os Ambientes em que as Tarefas Devem ser Executadas 148 | 149 | $schedule->command('foo')->monthly()->environments('production'); 150 | 151 | #### Indicando se a Execução da Tarefa Deve ser Relizada Mesmo Quando Aplicação Está em Manutenção 152 | 153 | $schedule->command('foo')->monthly()->evenInMaintenanceMode(); 154 | 155 | #### Permitindo que a Tarefa Seja Executada Apenas Quando o Retorno do Callback Seja Verdadeiro 156 | 157 | $schedule->command('foo')->monthly()->when(function() 158 | { 159 | return true; 160 | }); 161 | 162 | #### Envie um E-mail com o resultado da tarefa. 163 | 164 | $schedule->command('foo')->sendOutputTo($filePath)->emailOutputTo('foo@example.com'); 165 | 166 | > **Note:** You must send the output to a file before it can be mailed. 167 | 168 | #### Envie o resultado da tarefa agendada para um diretório específico 169 | 170 | $schedule->command('foo')->sendOutputTo($filePath); 171 | 172 | #### Ping uma URL depois que a tarefa executar 173 | 174 | $schedule->command('foo')->thenPing($url); 175 | 176 | Usando a método `thenPing($url)` requere que a biblioteca Guzzle HTTP esteja instalada. Você pode adicionar a Guzzle 5 no seu projeto adicionando no seu arquivo `composer.json a seguinte linha: 177 | 178 | "guzzlehttp/guzzle": "~5.0" 179 | -------------------------------------------------------------------------------- /bus.md: -------------------------------------------------------------------------------- 1 | # Command Bus 2 | 3 | - [Introdução](#introduction) 4 | - [Criando Comandos](#creating-commands) 5 | - [Despachando Commandos](#dispatching-commands) 6 | - [Comandos Queued](#queued-commands) 7 | - [Comandos em Pipeline](#command-pipeline) 8 | 9 | 10 | ## Introdução 11 | 12 | O comando Bus do Laravel é um método conveniente de encapsulamento de tarefas que sua aplicação precisa executar em um "commands"(comando) simples, e facil de entender. Para nos ajudar a entender o propósito dos comandos, vamos imaginar que estamos construindo uma aplicação que permita que os usuários comprem podcasts. 13 | 14 | Quando o usuário compra podcast, existem uma variedade de coisas que precisam acontecer. Por exemplo, nos podemos necessitar carregar o cartão de crédito do usuário, registrar a compra no banco de dados, e mandar um e-mail de confirmação de compra. Talvez, também precisaremos realizar algum tipo de validação para saber ser o usuário é autorizado a comprar podcasts. 15 | 16 | Nos podemos colocar toda essa lógica dentro do método do controlador(controller); contudo, isso teria várias desvantagens. A primeira disvatagem é que nosso controlador provavelmente lida com várias outras ações de entrada HTTP, e incluir uma lógica complicada em cada método no controlador logo irá inchar nosso controlador(controller) e com isso fazer com que o mesmo seja dificil de ler. Segundo, é difícil de reusar a lógica de compra de podcast fora do contexto do controlador. Terceiro, é mais difícil para realizar os testes unitários do comando, como também temos que gerar uma solicitação HTTP stub e fazer uma requisição inteira para aplicação para testar a lógica da compra do podcast. 17 | 18 | Ao invés de colocar esta lógica no controlador(controller), nos podemos escolher encapsular isto com o objeto "command" (comando), como o comando `PurchasePodcast`(ComparaPodcast). 19 | 20 | 21 | ## Criando Comandos 22 | 23 | O artisan CLI pode gerar uma nova classe de comento usando o comando `make:command`: 24 | 25 | php artisan make:command PurchasePodcast 26 | 27 | A nova classe gerada será alocada no diretório `app/Commands`. Por padrão, o comando contém dois métodos: o contrutor e o método `handle`. É claro que, o contrutor permite que você passe qualquer objeto relavante para o comando, enquanto o método `handle` executa o comando, Por exemplo: 28 | 29 | class PurchasePodcast extends Command implements SelfHandling { 30 | 31 | protected $user, $podcast; 32 | 33 | /** 34 | * Create a new command instance. 35 | * 36 | * @return void 37 | */ 38 | public function __construct(User $user, Podcast $podcast) 39 | { 40 | $this->user = $user; 41 | $this->podcast = $podcast; 42 | } 43 | 44 | /** 45 | * Execute the command. 46 | * 47 | * @return void 48 | */ 49 | public function handle() 50 | { 51 | // Handle the logic to purchase the podcast... 52 | 53 | event(new PodcastWasPurchased($this->user, $this->podcast)); 54 | } 55 | 56 | } 57 | 58 | O méotodo `handle` também pode tipar tipar dependencias, e elas irão ser automaticamente injetadoas pelo [service container](/docs/{{version}}/container). Por exemplo: 59 | 60 | /** 61 | * Execute the command. 62 | * 63 | * @return void 64 | */ 65 | public function handle(BillingGateway $billing) 66 | { 67 | // Handle the logic to purchase the podcast... 68 | } 69 | 70 | 71 | ## Despachando Comandos 72 | 73 | Então, umas vez que criamos o comando, como poderemos despacha-lo? É claro que, nos podemos chamar o método `handle` diretamento; entretanto, há várias vantagens em despachar o comando por meio do Laravel "command bus", essas serão discutidas mais tarde. 74 | 75 | Se você der uma olhada no controller base da sua aplicação, você verá a trait `DispatchesCommands`. Esta trait nos permite chmar o méotodo `dispatch` de qualquer um de nossos controllers. Por exemplo: 76 | 77 | public function purchasePodcast($podcastId) 78 | { 79 | $this->dispatch( 80 | new PurchasePodcast(Auth::user(), Podcast::findOrFail($podcastId)) 81 | ); 82 | } 83 | O comando bus irá cuidar da execução do comando e chamar o container IoC para injetar qualquer dependência necessária ao método `handle`. 84 | 85 | Você pode adicionar a trait `Illuminate\Foundation\Bus\DispatchesCommands` em qualquer classe que você desejar. Se você gostaria de receber a instância do comando bus por meio do contrutor de qualquer de suas classes, você pode sugerir o tipar a interface `Illuminate\Contracts\Bus\Dispatcher`. Finanlmente, você pode também usar a fachada `Bus`para rapidamente dipachar comandos: 86 | 87 | Bus::dispatch( 88 | new PurchasePodcast(Auth::user(), Podcast::findOrFail($podcastId)) 89 | ); 90 | 91 | ### Mapeando Propriedades do comando a partir da requests 92 | 93 | Isso é bem comum para mapear variáveis de requests(requisições) HTTP em comandos. Então, ao invés de forçar você a fazer isto manualmente para cada requisição, Laravel disponibiliza alguns métodos helpers para tornar isso mais fácil. Vamos dar uma olhada no método `dispatchFrom` disponível na trait `DispatchesCommands`. 94 | 95 | $this->dispatchFrom('Command\Class\Name', $request); 96 | 97 | Este método irá examinar o construtor da classe comando concedida, e em seguida, extrai variáveis da requisição HTTP( ou qualquer oturo objeto `ArrayAccess` ) para preencher os parâmetros do construtor do comando. Assim, se a nossa classe comando aceitar uma vaiável `firstName` em seu construtor, o comando bus tentará puxar o parâmetro `firstName` a partir da requisição HTTP. 98 | 99 | Você também pode passar um array como o terceiro argumento para o método `dispatchFrom`. Este array irá ser usado para preecher qualquer parâmetro do contrutor que não estiver disponível na request. 100 | 101 | $this->dispatchFrom('Command\Class\Name', $request, [ 102 | 'firstName' => 'Taylor', 103 | ]); 104 | 105 | 106 | ## Comandos Queued 107 | 108 | O comando bus não serve apenas para sincronizar jobs(tarefas agendadas) que são executados durante o ciclo requisição atual, mas também servem como a principal maneira de construir jobs em fila no Laravel. Então, como vamos instruir o comando bus para enfileirar o nosso job para o processamento em segundo plano ao invés de executa-lo sincronizadamente? Isto é fácil. Primeiramente, quando estivermos gerando um novo comando, devemos adicionar a flag (mais um parâmetro) `--queued` ao comando: 109 | 110 | php artisan make:command PurchasePodcast --queued 111 | 112 | Como você vai ver, isso adiciona mais algumas funcionalidades para comando, ou seja, a interface `Illuminate\Contracts\Queue\ShouldBeQueued` e a trait `SerializesModels`. Estes instruem o comando bus a enfileirar os comandos, bem como graciosamente serializa e desserializa qualquer modelo Eloquent do seu comando armazenando como propriedades. 113 | 114 | Se você desejar converter a um comando existente em um comando queued, simplesminte implemente a interface `Illuminate\Contracts\Queue\ShouldBeQueued` na classe manualmente. Esta interface não contém métódos, e serve apenas como uma "marker interface"(interface marcadora) para o despachante. 115 | 116 | Em seguida, apenas escreva seu comando normalmente. Quando você dispacha isto para o "bus" o bus será automaticamente enfileirado no processamento em segundo plano. Isto não tem como ser mais fácil. 117 | 118 | Para mais informações de como interagir com os comandos queued, veja a documentação completa [queue documentation](/docs/{{version}}/queues). 119 | 120 | 121 | ## Comandos em Pipeline 122 | 123 | Antes de um comando ser despachado ao manipulador, você pode passar isso por meio de outras classes em um "pipeline". Comando pipes funcionam como um middleware HTTP, exceto para seus comandos! Por exemplo, um comando pipe pode envolver todo a operação do comando dentro de uma transação com banco de dados, ou simplesmente registrar a sua execução. 124 | 125 | Para adicionar o pipe em seu comando bus, chame o méotodo `pipeThrough` do despachante a partir do seu método `App\Providers\BusServiceProvider::boot`: 126 | 127 | $dispatcher->pipeThrough(['UseDatabaseTransactions', 'LogCommand']); 128 | 129 | O comando pipe é definido com o método `handle`, apenas como um middleware: 130 | 131 | class UseDatabaseTransactions { 132 | 133 | public function handle($command, $next) 134 | { 135 | return DB::transaction(function() use ($command, $next) 136 | { 137 | return $next($command); 138 | }); 139 | } 140 | 141 | } 142 | 143 | As classes comando pipe são resolvidas através do [IoC container](/docs/{{version}}/container), então sinta-se livre para tipar qualquer dependencia que você precisar dentro dos seus contrutores. 144 | 145 | Você pode até mesmo definir um `Closure` como um comando pipe: 146 | 147 | $dispatcher->pipeThrough([function($command, $next) 148 | { 149 | return DB::transaction(function() use ($command, $next) 150 | { 151 | return $next($command); 152 | }); 153 | }]); 154 | -------------------------------------------------------------------------------- /cache.md: -------------------------------------------------------------------------------- 1 | # Cache 2 | 3 | - [Configuração](#configuration) 4 | - [Uso do Cache](#cache-usage) 5 | - [Incrementação & Decrementação](#increments-and-decrements) 6 | - [Marcações de Cache](#cache-tags) 7 | - [Cache Events](#cache-events) 8 | - [Cache no banco de dados](#database-cache) 9 | - [Memcached Cache](#memcached-cache) 10 | - [Redis Cache](#redis-cache) 11 | 12 | 13 | ## Configuração 14 | 15 | O Laravel fornece uma API unificada para vários sistemas de cache. A configuração do cache do laravel fica em `config/cache.php`. Neste arquivo você pode especificar o driver que você gostaria de usar por padrão em toda a sua aplicação. O Laravel suporta ferramentas como [Memcached](http://memcached.org) e [Redis](http://redis.io). 16 | 17 | O arquivo de configuração do cache também contém várias outras opções, que são documentadas dentro do arquivo. Sendo assim, certifique-se de ler estas opções. Por padrão, o Laravel é configurado para usar o drive `file`, que armazena objetos serializados no sistema de arquivos. Para grandes aplicações, recomenda-se que você utilize uma cache de in-memory(Verificar esse termo) como Memcached ou APC. Você pode ter várias configurações de cache para o mesmo driver. 18 | 19 | Antes de usar o Redis com o Laravel, vc precisará instalar o pacote `predis/predis` (~1.0) via Composer. 20 | 21 | 22 | ## Uso do Cache 23 | 24 | #### Gravando um item no Cache 25 | 26 | Cache::put('key', 'value', $minutes); 27 | 28 | #### Usando objetos do Carbon para a expiração 29 | 30 | $expiresAt = Carbon::now()->addMinutes(10); 31 | 32 | Cache::put('key', 'value', $expiresAt); 33 | 34 | #### Gravando um item no Cache caso ele não exista 35 | 36 | Cache::add('key', 'value', $minutes); 37 | O método `add` retornará `true` se o item foi realmente **adicionado** para o cache. Caso contrário, retornará `false`. 38 | 39 | #### Verificando se um Cache existe 40 | 41 | if (Cache::has('key')) 42 | { 43 | // 44 | } 45 | 46 | #### Recuperando um item do Cache 47 | 48 | $value = Cache::get('key'); 49 | 50 | #### Recuperando um item ou retornando um valor default 51 | 52 | $value = Cache::get('key', 'default'); 53 | 54 | $value = Cache::get('key', function() { return 'default'; }); 55 | 56 | #### Gravando um item no Cache permanentemente 57 | 58 | Cache::forever('key', 'value'); 59 | 60 | Algumas vezes você pode querer recuperar um item do cache, mas também armazenar um valor default se o item requisitado não existir. Você pode fazer isto utilizando o método `Cache::remember`: 61 | 62 | $value = Cache::remember('users', $minutes, function() 63 | { 64 | return DB::table('users')->get(); 65 | }); 66 | 67 | Você também pode combinar os métodos `remember` e `forever`: 68 | 69 | $value = Cache::rememberForever('users', function() 70 | { 71 | return DB::table('users')->get(); 72 | }); 73 | 74 | Note que todos os itens gravados no cache são serializados, neste caso, você fica livre para armazenar qualquer tipo de dado. 75 | 76 | #### Puxando um item do Cache 77 | 78 | Se você precisar recuperar um item do cache e, em seguida, deletá-lo, você pode usar o método `pull`: 79 | 80 | $value = Cache::pull('key'); 81 | 82 | #### Removendo um item do Cache 83 | 84 | Cache::forget('key'); 85 | 86 | #### Access Specific Cache Stores 87 | 88 | When using multiple cache stores, you may access them via the `store` method: 89 | 90 | $value = Cache::store('foo')->get('key'); 91 | 92 | 93 | ## Incrementando & Desincrementando 94 | 95 | Todos os drivers, exceto `database`, suportam as operações `increment` e `decrement`: 96 | 97 | #### Incrementando um valor 98 | 99 | Cache::increment('key'); 100 | 101 | Cache::increment('key', $amount); 102 | 103 | #### Desincrementando um valor 104 | 105 | Cache::decrement('key'); 106 | 107 | Cache::decrement('key', $amount); 108 | 109 | 110 | ## Marcações de Cache 111 | 112 | > **Nota:** As marcações de cache, não são suportadas quando se usam os drivers `file` ou `database`. Além disso, quando usamos várias marcações em caches que são armazenados "para sempre", o desempenho será melhor com um driver como `memcached`, que limpa automaticamente registros obsoletos. 113 | 114 | #### Acessando um Cache com uma marcação 115 | 116 | As marcações, permitem que você marque os items relacionados ao cache, em seguida, limpe todos os caches marcados com um nome dado. Para acessar um cache marcado, use o método `tags`. 117 | 118 | Você pode armazenar um cache passando um array dos nomes das marcações como argumentos ou como um array com os nomes das marcações: 119 | 120 | Cache::tags('people', 'authors')->put('John', $john, $minutes); 121 | 122 | Cache::tags(['people', 'artists'])->put('Anne', $anne, $minutes); 123 | 124 | Você pode usar qualquer método de armazenamento de cache em combinação com as marcações, incluindo `remember`, `forever` e `rememberForever`. Você também pode acessar itens que estão no cache oriundos das marcações de cache, também pode usar outros métodos de cache como `increment` e `decrement`. 125 | 126 | #### Acessando items em um Cache marcado 127 | 128 | Para acessar um cache marcado, passe o array das tags usadas anteriormente para armazenar. 129 | 130 | $anne = Cache::tags('people', 'artists')->get('Anne'); 131 | 132 | $john = Cache::tags(['people', 'authors'])->get('John'); 133 | 134 | Você pode limpar todos os itens marcados com um nome ou array de nomes. Por exemplo, nesta declaração removeremos todas as marcações de cache com `people`, `author` ou ambos. Então, "Anne" e "John" seriam removidos do cache: 135 | 136 | Cache::tags('people', 'authors')->flush(); 137 | 138 | Sendo assim, este outro código removerá somente caches marcados com `authors`. Então "John" será removido, mas "Anne", não. 139 | 140 | Cache::tags('authors')->flush(); 141 | 142 | 143 | ## Eventos Cache 144 | 145 | Para executar código em todas as operações de cache, você pode escutar (ou rastrear, procurar) por eventos disparados pelo cache: 146 | 147 | Event::listen('cache.hit', function($key, $value) { 148 | // 149 | }); 150 | 151 | Event::listen('cache.missed', function($key) { 152 | // 153 | }); 154 | 155 | Event::listen('cache.write', function($key, $value, $minutes) { 156 | // 157 | }); 158 | 159 | Event::listen('cache.delete', function($key) { 160 | // 161 | }); 162 | 163 | 164 | ## Cache do banco de dados 165 | 166 | Quando usar o drive de cache `database` , você precisará configurar uma tabela no que contém os itens do cache. Veja um exemplo `Schema` abaixo: 167 | 168 | Schema::create('cache', function($table) 169 | { 170 | $table->string('key')->unique(); 171 | $table->text('value'); 172 | $table->integer('expiration'); 173 | }); 174 | 175 | 176 | #### Memcached Cache 177 | 178 | Usar o Mencached cache requere que o [Pacote Memcached PECL](http://pecl.php.net/package/memcached) seja instalado. 179 | 180 | Por padrão [configuração](#configuration) usa TCP/IP baseado no [Memcached::addServer](http://php.net/manual/en/memcached.addserver.php): 181 | 'memcached' => array( 182 | array('host' => '127.0.0.1', 'port' => 11211, 'weight' => 100), 183 | ), 184 | 185 | Você pode também definir a opção `host` para um caminho de socket UNIX. Se você fizer isto, a opção `port` deve ser definida com o valor `0`: 186 | 187 | 'memcached' => array( 188 | array('host' => '/var/run/memcached/memcached.sock', 'port' => 0, 'weight' => 100), 189 | ), 190 | 191 | 192 | #### Cache Redis 193 | 194 | Veja [Configuração Redis](/docs/redis#configuration) 195 | -------------------------------------------------------------------------------- /collections.md: -------------------------------------------------------------------------------- 1 | # Collections 2 | 3 | - [Introdução](#introduction) 4 | - [Uso Básico](#basic-usage) 5 | 6 | 7 | ## Introdução 8 | 9 | 10 | A classe `Illuminate\Support\Collection` um nativo, conveniente wrapper para trabalhar com arrays de dados. Por exemplo, dê uma olhada no seguinte código. Usaremos o helper `collect` para criar uma nova instância de uma coleção a partir de um array: 11 | 12 | $collection = collect(['taylor', 'abigail', null])->map(function($name) 13 | { 14 | return strtoupper($name); 15 | }) 16 | ->reject(function($name) 17 | { 18 | return empty($name); 19 | }); 20 | 21 | Como você pode ver, a classe `Collection` permite que você chame encadeadamento métodos para realizar nativamente mapeamento e redução do array subjacente. Em geral, todo método `Collection` retorna uma nova instância inteira de `Collection`. Para mais detalhes, continue lendo! 22 | 23 | 24 | ## Uso Básico 25 | 26 | #### Criado Coleções 27 | 28 | Como mencionado acima, o helper `collect` retornará uma nova instância de `Illuminate\Support\Collection` para o array dado. Você pode também usar o comando `make` na classe `Collection`: 29 | 30 | $collection = collect([1, 2, 3]); 31 | 32 | $collection = Collection::make([1, 2, 3]); 33 | 34 | É claro, que objetos de coleções [Eloquent](/docs/{{version}}/eloquent) sempre retornam como instâncias de `Collection`; contudo, você deve se sentir livre para usar a classe `Collection` quando isto for conveniente para sua aplicação. 35 | 36 | #### Explore a Coleção 37 | 38 | Ao invés de listar todos os métodos (que são muitos) a Api de `Collection` é disponibilizada, dê uma olhada na [Na documentação da API para a classe](http://laravel.com/api/master/Illuminate/Support/Collection.html)! 39 | -------------------------------------------------------------------------------- /commands.md: -------------------------------------------------------------------------------- 1 | # Artisan Development 2 | 3 | - [Introdução](#introduction) 4 | - [Construindo um Comando](#building-a-command) 5 | - [Registrando Comandos](#registering-commands) 6 | 7 | 8 | ## Introdução 9 | 10 | Além dos comandos fornecidos pelo Artisan, você pode também criar os seus comandos personalizados para trabalhar com sua aplicação. Você pode armazenar seus comandos personalizados no diretório `app/Console/Commands`; no entanto, você é livre para escolher a localização do seu diretório de armazenamento, desde que seus comandos possam ser carregados automaticamente baseados nas configurações do seu `composer.json`. 11 | 12 | 13 | ## Construindo um Comando 14 | 15 | ### Gerando a Classe 16 | 17 | Para criar um novo comando, você pode usar o comando Artisan `make:console`, que gerará um esboço do comando para ajudar você a começar: 18 | 19 | #### Gerando uma Nova Classe de Comando 20 | 21 | php artisan make:console FooCommand 22 | 23 | O comando acima irá gerar a classe em `app/Console/Commands/FooCommand.php`. 24 | 25 | Quando nos estamos criando um comando, a opção `--command` pode ser usada para atribuir o nome do comando no terminal: 26 | 27 | php artisan make:console AssignUsers --command=users:assign 28 | 29 | ### Escrevendo o Comando 30 | 31 | Uma vez que o seu comando é gerado, você deve preencher o `nome` e `descrição` propriedades da classe, que irá ser utilizada quando seu comando for mostrado na tela de listagem `list`. 32 | 33 | O método `fire` irá ser chamado quando seu comando é executado. Você pode colocar qualquer lógica de comando neste método. 34 | 35 | ### Argumentos e Opções 36 | 37 | Os métodos `getArguments` e `getOptions` é onde você define qualquer parâmetro ou opção que o seu comando pode receber. 38 | Ambos os métodos retornam um array de comandos, que são descritos por uma lista de array de opções. 39 | 40 | Quando se está definindo `arguments` (parâmetros), os valores de definição do array representam o seguinte. 41 | 42 | [$name, $mode, $description, $defaultValue] 43 | 44 | O parâmetro `mode` oide ser qualquer um dos seguintes:`InputArgument::REQUIRED` ou `InputArgument::OPTIONAL`. 45 | 46 | Quando estamos definindo `options`, o valores de definição do array representam o seguinte: 47 | 48 | [$name, $shortcut, $mode, $description, $defaultValue] 49 | 50 | Para opções, o parâmetro `mode` pode ser: `InputOption::VALUE_REQUIRED`, `InputOption::VALUE_OPTIONAL`, `InputOption::VALUE_IS_ARRAY`, `InputOption::VALUE_NONE`. 51 | 52 | O modo `VALUE_IS_ARRAY` indica que a chave pode ser usada várias vezes ao chamar o comando: 53 | 54 | InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY 55 | 56 | O que então permitiria este comando: 57 | 58 | php artisan foo --option=bar --option=baz 59 | 60 | A opção `VALUE_NONE` indica que a opção é simplesmente usada como uma "chave": 61 | 62 | php artisan foo --option 63 | 64 | ### Recuperando o Input 65 | 66 | Enquanto o seu comando é executado, você obviamente precisa do acesso aos valores para os argumentos e opções aceitas pela sua aplicação. Para isto, você pode usar os métodos `argument` e `option`: 67 | 68 | #### Recuperando O Valor De Um Argumento de Comando 69 | 70 | $value = $this->argument('name'); 71 | 72 | #### Recuperando Todos os Argumentos 73 | 74 | $arguments = $this->argument(); 75 | 76 | #### Recuperando O Valor De Uma Opção de Comando 77 | 78 | $value = $this->option('name'); 79 | 80 | #### Recuperando todas as Opções 81 | 82 | $options = $this->option(); 83 | 84 | ### Escrevendo Output (Saídas) 85 | 86 | Para mandar saídas para o seu console, você pode usar os métodos de `info`, `comment`, `question` and `error`. Cada um destes métodos usará a cor ANSI apropriada para sua finalidade. 87 | 88 | #### Enviando Informação Para o Console 89 | 90 | $this->info('Display this on the screen'); 91 | 92 | #### Enviando Uma Mensagem De Erro Para O Console 93 | 94 | $this->error('Something went wrong!'); 95 | 96 | ### Fazendo Perguntas 97 | 98 | Você pode também usar os métodos `ask` e `confirm` para para solicitar entradas no console para o usuário: 99 | 100 | #### Fazendo Perguntas Ao Usuário 101 | 102 | $name = $this->ask('What is your name?'); 103 | 104 | #### Pergutando Ao Usuário Por Uma Entrada Secreta 105 | 106 | $password = $this->secret('What is the password?'); 107 | 108 | #### Pergutando O Usuário Por Confirmação 109 | 110 | if ($this->confirm('Do you wish to continue? [yes|no]')) 111 | { 112 | // 113 | } 114 | 115 | Você também pode especificar um valor default para o método `confirm`, que deve ser `true` ou `false` 116 | 117 | $this->confirm($question, true); 118 | 119 | ### Chamando Outros Comandos 120 | 121 | Algumas vezes você pode desejar chamar outros comandos a partir do seu. Você pode fazer isto usando o método `call`: 122 | 123 | $this->call('command:name', ['argument' => 'foo', '--option' => 'bar']); 124 | 125 | 126 | ## Registrando Comandos 127 | 128 | #### Registrando o Comando Artisan 129 | 130 | Uma vez que seu comando estiver pronto, você precisa registrar o mesmo com Artisan então ele ficará disponível para uso. Isto é geralmente feito no arquivo `app/Console/Kernel.php`. Dentro deste arquivo, você irá encontrar uma lista de comandos na propriedade `commands`. Para registrar o seu comando, você simplesmente deve adiciona-lo à esta lista. 131 | 132 | protected $commands = [ 133 | 'App\Console\Commands\FooCommand' 134 | ]; 135 | 136 | Quando o Artisan inicializar, todos os comandos listados na propriedade `commands` que serão resolvidos pelo [service container](/docs/{{version}}/container) e registrados no Artisan. 137 | 138 | -------------------------------------------------------------------------------- /configuration.md: -------------------------------------------------------------------------------- 1 | # Configuration 2 | 3 | - [Introdução](#introduction) 4 | - [Depois da Instalação](#after-installation) 5 | - [Acessando Valores de Configuração](#accessing-configuration-values) 6 | - [Configuração de Ambiente](#environment-configuration) 7 | - [Configuração de Caching](#configuration-caching) 8 | - [Modo de Manutenção](#maintenance-mode) 9 | - [URLs Amigáveis](#pretty-urls) 10 | 11 | 12 | ## Introdução 13 | 14 | Todos os arquivos de configuração para o framework Laravel são armazenados no diretório `config`. Cada opção é documentada, então sinta-se livre para dar uma olhada nos arquivos 15 | e se famialirizar com as opções disponíves pra você. 16 | 17 | 18 | ## Depois Da Instalação 19 | 20 | ### Nomeando sua aplicação 21 | 22 | Depois de instalar Laravel, você pode querer nomear a sua aplicação. Por padrão, o diretório `app` tem o namespace `App`, e é carregado automaticamente pelo Composer usando a [PSR-4 autoloading standard](http://www.php-fig.org/psr/psr-4/). Contudo, você pode mudar o namespace para o mesmo da sua aplicação, que você pode facilmente fazer por meio do comando Artisan `app:name`. 23 | 24 | Por exemplo, se sua aplicação é nomeada "Horsefly", você pode executar o seguinte comando a partir do diretório root da sua instalação: 25 | 26 | php artisan app:name Horsefly 27 | 28 | Renomear sua aplicação é totalmente opcional, e você é livre para manter o namespace `App` se você desejar. 29 | 30 | ### Outras Configurações 31 | 32 | Laravel precisa de poucas configurações de fora da caixa. Você é livre para começar a desenvolver! No entanto, você pode desejar revisar o arquivo `config/app.php` e sua documentação. Nela, contém várias opções como as de `timezone` (fuso-horário) e `locale` (localização) que você pode desejar mudar de acordo com a sua localização. 33 | 34 | 35 | Uma vez que o Laravel é instalado, você deve tambeḿ [configure your local environment](/docs/{{version}}/configuration#environment-configuration). 36 | 37 | > **Nota:** Você nunca deve ter a configuração `app.debug` definida como "true" no ambiente de produção da sua aplicação. 38 | 39 | 40 | ### Permissões 41 | 42 | Laravel pode requerer um conjunto de permissões para ser configurado: pastas dentro do diretório `storage` requerem permissões de acesso a escrita no servidor. 43 | 44 | 45 | ## Acessando Valores de Configuração 46 | 47 | Você pode facilmente acessar os valores de configurações usando a fachada `Config`: 48 | 49 | $value = Config::get('app.timezone'); 50 | 51 | Config::set('app.timezone', 'America/Chicago'); 52 | 53 | Você pode também usar o função helper `config`: 54 | 55 | $value = config('app.timezone'); 56 | 57 | 58 | ## Configuração de Ambiente 59 | 60 | Na maioria das vezes, é util ter diferentes valores de configurações baseados nos ambientes em que a aplicação está sendo executada. Por examplo, você pode desejar usar drivers de cache diferentes localmente do que você usa no servidor de produção. Isto é fácil, usando o ambiente baseado na configuração. 61 | 62 | Para isso ser fácil, Laravel utiliza a biblioteca PHP feita por Vance Lucar [DotEnv](https://github.com/vlucas/phpdotenv). Em uma instalação pura de laravel, o diretório rais da sua aplicação irá conter o arquivo `.env.example`. Se você instalar o Laravel via Composer, este arquvivo irá automaticamente ser renomeado por `.env`. Caso contrário, você deve renomear o arquvio manualmente. 63 | 64 | Todas as variáveis listadas neste arquvio serão carregadas na superglobal PHP `$_ENV` quando sua aplicação receber a requisição. Você pode usar o helper `env` para recuperar os valores das variáveis. Na verdade, se você revisar os arquivos de configuração do Laravel, você irá notar que várias das opções já usam este Helper! 65 | 66 | Sinta-se à vontade para modificar as suas variáveis de ambiente como for necessário para o seu servidor local, como também para seu ambiente de produção. No entanto, seu arquivo `.env` não deve ser commitado para sistema de controle de versionamento, desde que cada desenvolvedor / servidor que está usando sua aplicação possa requerer diferentes configurações de ambiente. 67 | 68 | Se você estiver desenvolvendo com um time, você pode querer continuar incluindo o arquivo `.env.example` na sua aplicação. Ao colocar valores place-holder no exemplo de arquivo de configuração, outros desenvolvedor no seu time podem claramente ver que o as variáveis de ambeinte são necessárias para a execução da sua aplicação. 69 | 70 | #### Acessando Ambiente Atual da Aplicação 71 | 72 | Você pode acessar o ambiente atual da sua aplicação por meio do método `environment` na instância de `Application`: 73 | 74 | $environment = $app->environment(); 75 | 76 | Você pode também passar argumento para o método `environment` para checar se o ambiente tem o mesmo valor do argumento passado: 77 | 78 | if ($app->environment('local')) 79 | { 80 | // The environment is local 81 | } 82 | 83 | if ($app->environment('local', 'staging')) 84 | { 85 | // The environment is either local OR staging... 86 | } 87 | 88 | Para obeter a instância da aplicação, resolva o contrato `Illuminate\Contracts\Foundation\Application` via o [container de serviços](/docs/{{version}}/container). É claro que, se você você estiver dentro de um [provedor de serviço](/docs/{{version}}/providers), a instância da aplicação é disponibilizada via a instância da variável `$this->app`. 89 | 90 | A instância da aplicação pode também ser acessada via o helper `app` ou pela fachada `App`: 91 | 92 | $environment = app()->environment(); 93 | 94 | $environment = App::environment(); 95 | 96 | 97 | ## Configuração Caching 98 | 99 | Para da a sua aplicação um empurrão na velocidade, você pode armazenar em cache todos os seus arquivos de configuração em um único arquivo usando o comando Artisan `config:cache`. Iso irá combinar todas as opções do configuração da sua aplicação em um único arquivo que pode ser carregado rapidamente pelo framework. 100 | 101 | Você deve executar normalmente o comando `config:cache` como parte da sua rotina de deploy. 102 | 103 | 104 | ## Modo de Manutenção 105 | 106 | Quando sua aplicação estier em modo de manutenção, uma view customizada será exibida para todas as requisições a aplicação. Isto faz com que seja fácil de "desativar" a sua aplicação enquanto ela é atualizada ou quando você efetuando uma manutenção. A checage se a aplicação está no modo de manutenção é incluída por padrão na pilha do middleware da sua aplicação. Se a aplicação estiver em modo de manutenção, uma `HttpException` (exceção HTTP) será lançada ao usuário com o código de status 503. 107 | 108 | Para ativar o modo de manutenção, simplesmente execute o comando Artisan `down`: 109 | 110 | php artisan down 111 | 112 | Para disativar o modo de manutenção, use o comando `up`: 113 | 114 | php artisan up 115 | 116 | ### Template de reposta Do Modo de Manutenção 117 | 118 | A template padrão para reposta do modo de manutenção, é localizado no diretório `resources/views/errors/503.blade.php`. 119 | 120 | ### Modo de manutenção e Queues 121 | 122 | Enquanto sua aplicação estiver no modo de manutenção, nenhuma [queued jobs](/docs/{{version}}/queues) serão tratada. As queues continuarão sendo tratadas normalmente uma vez que a sua aplicação sair do modo de manutenção. 123 | 124 | 125 | ## URLs Amigáveis 126 | 127 | ### Apache 128 | 129 | O framework envia com o arquivo `public/.htaccess` o que é usando para permitir URLs sem `index.php`. Se você usa Apache como webserver da sua aplicação Laravel, certifique-se de ativar o módulo `mod_rewrite`. 130 | 131 | Se o arquivo `.htaccess` que vem com a aplicação Laravel não function com a sua instalação do Apache, teste com esta: 132 | 133 | Options +FollowSymLinks 134 | RewriteEngine On 135 | 136 | RewriteCond %{REQUEST_FILENAME} !-d 137 | RewriteCond %{REQUEST_FILENAME} !-f 138 | RewriteRule ^ index.php [L] 139 | 140 | Se o seu web host não permitir a opção `FollowSymlinks`, teste substituí-lo com `Options +SymLinksIfOwnerMatch`. 141 | 142 | ### Nginx 143 | 144 | No Nginx, a seguinte diretiva na sua configuração de site permitira URLs "amigáveis": 145 | 146 | location / { 147 | try_files $uri $uri/ /index.php?$query_string; 148 | } 149 | É claro que, quando estiver usando a [Homestead](/docs/{{version}}/homestead), URLs amigáveis serão configuradas automaticamente. 150 | -------------------------------------------------------------------------------- /contracts.md: -------------------------------------------------------------------------------- 1 | # Contracts 2 | 3 | - [Introdução](#introduction) 4 | - [Why Contracts?](#why-contracts) 5 | - [Contract Reference](#contract-reference) 6 | - [How To Use Contracts](#how-to-use-contracts) 7 | 8 | 9 | ## Introdução 10 | 11 | Os contratos Laravel são um conjunto de interfaces que definem o núcleo de serviços que são fornecidos pelo framework. Por exemplo, o contrato `Queue` defini o os métodos necessários para queueing jobs(enfileirar trabalhos), enquanto o contrato `Mailer` defini os métodos necessários para o envio e-mails. 12 | 13 | Cada contratos tem uma implementação correspondente fornecidade pelo o frameork. Por exemplo, Laravel fornece a implementação de `Queue` com a variedade de drivers, e a implementação de `Mailer` é alimentada pelo [SwiftMailer](http://swiftmailer.org/). 14 | 15 | Todo os contratos de Laravel vivem nos [seus proprios repositórios GitHub](https://github.com/illuminate/contracts). Isto fornece um rápido ponto de referência para todos os contratos disponíveis, bem como um pacote único, desacoplado que pode ser utilizado por outros desenvolvedores de pacotes. 16 | 17 | 18 | ## Porque Contratos ? 19 | 20 | Você pode ter várias questões sobre contratos. Porque usar interfaces como um todo? Não usar interfaces é mais complicado? 21 | 22 | Vamos destrinchar as razões para usar inteface para os seguintes tópicos: baixo acoplamento e simplicidade. 23 | 24 | ### Baixo Acoplamento 25 | 26 | Primeiro, vamos revisar algum código que estreitamente ligado a implementação de cache. Considere o seguinte: 27 | 28 | cache = $cache; 46 | } 47 | 48 | /** 49 | * Retrieve an Order by ID. 50 | * 51 | * @param int $id 52 | * @return Order 53 | */ 54 | public function find($id) 55 | { 56 | if ($this->cache->has($id)) 57 | { 58 | // 59 | } 60 | } 61 | 62 | } 63 | 64 | Nesta classe, o código é estreitamente acoplado para uma dada implementação de cache. Isto é estreitamente acoplado porque nos dependemos de uma classe Cache concreta, de um pacote vendor. Se a API do pacote muda nosso código também deve mudar. 65 | 66 | 67 | Da mesma forma, se nos substituirmos nossa tecnologia cache subjacente (Memcached) com outra tecnologia (Redis), que novamente iremos ter que modificar nosso repositório. Nosso repositório deve não ter muito conhecimento a respeito a quem está fornecendo-lhe dados ou como eles estão fornecedo-os. 68 | 69 | ** Aos invés desta abordagem, nos podemos melhorar nosso código pela dependência de uma simples interface agnóstica do vendor:** 70 | 71 | cache = $cache; 86 | } 87 | 88 | } 89 | 90 | Agora o código é não acoplado para qualquer vendor específico, ou até mesmo Laravel. Uma vez que os pacotes de contratos contenham nenhuma implementação e dependência, você pode facilmente escrever uma implementação alternativa de qualquer contrato dado, permitindo você possa substituir sua implementação cache sem modificar qualquer dos seus códigos consumidores de cache. 91 | 92 | ### Simplicidade 93 | 94 | Quando todos os serviços do Laravel são bem definidos dentro interfaces simples, isto é muito fácil de determinar a funcionalidade oferecida por um determinado serviço. ** Os contratos servem como uma documentação sucinta às funcionalidades do framework Laravel.** 95 | 96 | Além disso, quando você depende de interfaces simples, seu código é mais fácil de entender e manter. Ao invés de inspecionar dentro dos métodos que estão disponívels para você dentro de grande e complicada classe, você pode se referir a uma simples e limpa interface. 97 | 98 | 99 | ## Referência do Contrato 100 | 101 | Isto é a referencia para a maioria dos contratos do Laravel, bem como as "fachadas" Laravel contrapartidas: 102 | 103 | Contract | Laravel 4.x Facade 104 | ------------- | ------------- 105 | [Illuminate\Contracts\Auth\Guard](https://github.com/illuminate/contracts/blob/master/Auth/Guard.php) | Auth 106 | [Illuminate\Contracts\Auth\PasswordBroker](https://github.com/illuminate/contracts/blob/master/Auth/PasswordBroker.php) | Password 107 | [Illuminate\Contracts\Bus\Dispatcher](https://github.com/illuminate/contracts/blob/master/Bus/Dispatcher.php) | Bus 108 | [Illuminate\Contracts\Cache\Repository](https://github.com/illuminate/contracts/blob/master/Cache/Repository.php) | Cache 109 | [Illuminate\Contracts\Cache\Factory](https://github.com/illuminate/contracts/blob/master/Cache/Factory.php) | Cache::driver() 110 | [Illuminate\Contracts\Config\Repository](https://github.com/illuminate/contracts/blob/master/Config/Repository.php) | Config 111 | [Illuminate\Contracts\Container\Container](https://github.com/illuminate/contracts/blob/master/Container/Container.php) | App 112 | [Illuminate\Contracts\Cookie\Factory](https://github.com/illuminate/contracts/blob/master/Cookie/Factory.php) | Cookie 113 | [Illuminate\Contracts\Cookie\QueueingFactory](https://github.com/illuminate/contracts/blob/master/Cookie/QueueingFactory.php) | Cookie::queue() 114 | [Illuminate\Contracts\Encryption\Encrypter](https://github.com/illuminate/contracts/blob/master/Encryption/Encrypter.php) | Crypt 115 | [Illuminate\Contracts\Events\Dispatcher](https://github.com/illuminate/contracts/blob/master/Events/Dispatcher.php) | Event 116 | [Illuminate\Contracts\Filesystem\Cloud](https://github.com/illuminate/contracts/blob/master/Filesystem/Cloud.php) |   117 | [Illuminate\Contracts\Filesystem\Factory](https://github.com/illuminate/contracts/blob/master/Filesystem/Factory.php) | File 118 | [Illuminate\Contracts\Filesystem\Filesystem](https://github.com/illuminate/contracts/blob/master/Filesystem/Filesystem.php) | File 119 | [Illuminate\Contracts\Foundation\Application](https://github.com/illuminate/contracts/blob/master/Foundation/Application.php) | App 120 | [Illuminate\Contracts\Hashing\Hasher](https://github.com/illuminate/contracts/blob/master/Hashing/Hasher.php) | Hash 121 | [Illuminate\Contracts\Logging\Log](https://github.com/illuminate/contracts/blob/master/Logging/Log.php) | Log 122 | [Illuminate\Contracts\Mail\MailQueue](https://github.com/illuminate/contracts/blob/master/Mail/MailQueue.php) | Mail::queue() 123 | [Illuminate\Contracts\Mail\Mailer](https://github.com/illuminate/contracts/blob/master/Mail/Mailer.php) | Mail 124 | [Illuminate\Contracts\Queue\Factory](https://github.com/illuminate/contracts/blob/master/Queue/Factory.php) | Queue::driver() 125 | [Illuminate\Contracts\Queue\Queue](https://github.com/illuminate/contracts/blob/master/Queue/Queue.php) | Queue 126 | [Illuminate\Contracts\Redis\Database](https://github.com/illuminate/contracts/blob/master/Redis/Database.php) | Redis 127 | [Illuminate\Contracts\Routing\Registrar](https://github.com/illuminate/contracts/blob/master/Routing/Registrar.php) | Route 128 | [Illuminate\Contracts\Routing\ResponseFactory](https://github.com/illuminate/contracts/blob/master/Routing/ResponseFactory.php) | Response 129 | [Illuminate\Contracts\Routing\UrlGenerator](https://github.com/illuminate/contracts/blob/master/Routing/UrlGenerator.php) | URL 130 | [Illuminate\Contracts\Support\Arrayable](https://github.com/illuminate/contracts/blob/master/Support/Arrayable.php) |   131 | [Illuminate\Contracts\Support\Jsonable](https://github.com/illuminate/contracts/blob/master/Support/Jsonable.php) |   132 | [Illuminate\Contracts\Support\Renderable](https://github.com/illuminate/contracts/blob/master/Support/Renderable.php) |   133 | [Illuminate\Contracts\Validation\Factory](https://github.com/illuminate/contracts/blob/master/Validation/Factory.php) | Validator::make() 134 | [Illuminate\Contracts\Validation\Validator](https://github.com/illuminate/contracts/blob/master/Validation/Validator.php) |   135 | [Illuminate\Contracts\View\Factory](https://github.com/illuminate/contracts/blob/master/View/Factory.php) | View::make() 136 | [Illuminate\Contracts\View\View](https://github.com/illuminate/contracts/blob/master/View/View.php) |   137 | 138 | 139 | ## Como Usar Contratos 140 | 141 | Então, como você pode começar a implementação de contrato? Na verdade é muito simples. Muitos tipos de classes em Laravel são resolvidas pro meio do [container de serviços](/docs/{{version}}/container), incluíndo controladores, listeners(ouvidores) de eventos, queue jobs(trabalhos em fila), e até mesmo Closures de rota. Então, para começar a implementação de um contrato, você pode apenas "tipar" a interface no contrutor da classe que está sendo resolvida. Por exemplo, de uma olhada neste manipulador de evento. 142 | 143 | redis = $redis; 165 | } 166 | 167 | /** 168 | * Handle the event. 169 | * 170 | * @param NewUserRegistered $event 171 | * @return void 172 | */ 173 | public function handle(NewUserRegistered $event) 174 | { 175 | // 176 | } 177 | 178 | } 179 | 180 | Quando os listener de evento é resolvido, o container de serviço irá ler a tipagem no construtor da classse, e irá injetar o valor apropriado. Para aprender mais sobre como registrar as coisas no container de serviços, dê uma olhada na [documentação](/docs/{{version}}/container). 181 | 182 | -------------------------------------------------------------------------------- /contributing.md: -------------------------------------------------------------------------------- 1 | # Orientação Para Contribuições 2 | 3 | Se você estiver submetendo a documentação para a **versão estável atual** submeta isto para a branch correspondente. Por exemplo, documentação para Laravel 5.0 deve ser submetida para a branch 5.0. Documentação prentidas para o próximo lançamento do Laravel, deve ser submetida para a branch `master` 4 | -------------------------------------------------------------------------------- /contributions.md: -------------------------------------------------------------------------------- 1 | # Contribution Guide 2 | 3 | - [Relatar Bugs](#bug-reports) 4 | - [Discurssão sobre o Desenvolvimento do Core](#core-development-discussion) 5 | - [Quial Branch?](#which-branch) 6 | - [Vulnerabilidades de Segurança](#security-vulnerabilities) 7 | - [Estilo de Código](#coding-style) 8 | 9 | 10 | ## Relatar Reports 11 | 12 | Para encoragar a ativa colaboração, Laravel encoraja fortemente pull requests, não apenas relatório de bugs. "Relatar Bugs" pode também ser enviada em forma de pull request contendo um teste unitário que falhou. 13 | 14 | No entanto, se você enviar um relatório de bug, o problema deve conter um título e uma descrição clara do problema. Você deve incluir o máximo de informação relevante possível e uma amostra do código que mostra o problema. O objetivo de relatório de bugs é tonar mais fácil para si mesmo - e outros - replicar o bug e desenvolver a solução. 15 | 16 | Lembre-se, relatório de bugs foi criada com o intúito que outras pessoas com o seu mesmo problemas irão ser aptas de colaborar com você para resolver isto. Não espere que a relatório de bug verá qualquer atividade ou qualquer outra coisa e irá pular par resolver isto. Criar um relatório bug serve para ajudar a você mesmo e outros que começaram no caminho da solução de problemas. 17 | 18 | O código fonte do Laravel é gerenciado no Github, e lá existem repositórios para cada projeto Laravel: 19 | 20 | - [Laravel Framework](https://github.com/laravel/framework) 21 | - [Laravel Application](https://github.com/laravel/laravel) 22 | - [Laravel Documentation](https://github.com/laravel/docs) 23 | - [Laravel Cashier](https://github.com/laravel/cashier) 24 | - [Laravel Envoy](https://github.com/laravel/envoy) 25 | - [Laravel Homestead](https://github.com/laravel/homestead) 26 | - [Laravel Homestead Build Scripts](https://github.com/laravel/settler) 27 | - [Laravel Website](https://github.com/laravel/laravel.com) 28 | - [Laravel Art](https://github.com/laravel/art) 29 | 30 | 31 | ## Discurssão sobre o Desenvolvimento do Core 32 | 33 | Discurssão sobre bugs, novos recursos, e implementação de funcionalidade existentes ocorre no canal do IRC `#laravel-dev`(Freenode). Taylor Otwell, o mantenedor to Laravel, é normalmente presente no canal nos dias de semana das 8h da manhã as 5 da tarde (UTC-06:00 or America/Chicago), e esporadicamente presente no canal em outros horários. 34 | 35 | O canal do IRC `#laravel-dev` é aberto da todos. Todos são bem vindo as se juntar o canal tanto seja para participar ou simplesmente observar as discussões. 36 | 37 | 38 | ## Qual Branch? 39 | 40 | **Todas** as correções de bugs devem ser enviadas para o último branch estável. Correções de bugs **nunca** devem ser enviadas para a branch `master` a menos que enviem correçoes de funcionalidades que existem no proxímo lançamento. 41 | 42 | **Funcinalidades de Menor** proporção que são **totalmente compatíveis com as branchs anteriores** e também com a branch atual do Laravel poderão ser enviada para última branch estável do Laravel. 43 | 44 | **Funcionalidades de maior proporção** novos recursos devem ser sempre enviados para a branch `master`, que contém a próxima versão do Laravel. 45 | 46 | Se você incerto se sua funcionalidade é qualificada como principal ou menor, por favor pergunte a Taylor Otwell no canal do IRC `#laravel-dev` (Freenode). 47 | 48 | 49 | ## Vulnerabilidades de Segurança 50 | 51 | Se você discobrir uma falha de segurança no Lravel, por favor mande um e-mail para Taylor Otwell no endereço taylor@laravel.com. Todas as falhas de segurança serão prontamente corrigidas. 52 | 53 | 54 | ## Estilo de Código 55 | 56 | Laravel segue os padrões de código [PSR-4](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-4-autoloader.md) e a [PSR-1](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-1-basic-coding-standard.md). Em adição a estas normas, os seguintes padrões devem ser seguidos: 57 | 58 | - A declaração de namespace deve estar na mesma linha que ` 11 | ## Configuração 12 | 13 | O Laravel se conecta com banco de dados e executa consultas de forma extremamente simples. O arquivo de configuração é o `config/database.php`. Neste arquivo, você pode definir todas as suas conexões com os bancos de dados, e também especificar a conexão padrão. Neste arquivo, você encontra exemplos para se conectar com todos os bancos suportados. 14 | 15 | Atualmente, o Laravel suporta quatro sistemas de bancos de dados: MySQL, Postgres, SQLite, e SQL Server. 16 | 17 | 18 | ## Conexões de Leitura / Escrita 19 | 20 | As vezes, você deseja usar uma conexão do banco de dados para comandos SELECT, e uma para comandos INSERT, UPDATE, e DELETE. O Laravel torna isso possível, e as devidas conexões serão sempre usadas, esteja você usando "raw queries", o "query builder", ou o ORM Eloquent. 21 | 22 | Para ver como conexões de leitura / escrita devem ser configuradas, dê uma olhada neste exemplo: 23 | 24 | 'mysql' => [ 25 | 'read' => [ 26 | 'host' => '192.168.1.1', 27 | ], 28 | 'write' => [ 29 | 'host' => '196.168.1.2' 30 | ], 31 | 'driver' => 'mysql', 32 | 'database' => 'database', 33 | 'username' => 'root', 34 | 'password' => '', 35 | 'charset' => 'utf8', 36 | 'collation' => 'utf8_unicode_ci', 37 | 'prefix' => '', 38 | ], 39 | 40 | Observe que duas chaves foram adicionadas ao array de configuração: `read` e `write` (leitura e escrita). Essas duas chaves possuem valores de array contendo uma única chave: `host`. O resto das opções do banco de dados para conexões de`read` e `write` serão mescladas como array principal `mysql`. Então, nós so precisamos colocar itens nos arrays `read` e `write` se quisermos sobrescrever os valores do array principal. Então, neste casi, `192.168.1.1` será usado para a coneXão "read", enquanto `192.168.1.2` será usado para a conexão "write". As credeciais do banco de dados, o prefixo, conjunto de caracteres, e todas as outras opções do array proincipal `mysql`serão compartilhadas entre as duas conexões. 41 | 42 | 43 | ## Executando consultas 44 | 45 | Uma vez configurada sua conexão com o banco de dados, você pode executar consultas com a facade `DB`. 46 | 47 | #### Execuntando uma consultas Select 48 | 49 | $results = DB::select('select * from users where id = ?', [1]); 50 | 51 | O métodos `select` sempre retornará um `array` de resultados. 52 | 53 | You may also execute a query using named bindings: 54 | 55 | $results = DB::select('select * from users where id = :id', ['id' => 1]); 56 | 57 | #### Executando uma consulta Insert 58 | 59 | DB::insert('insert into users (id, name) values (?, ?)', [1, 'Dayle']); 60 | 61 | #### Executando uma consulta Update 62 | 63 | DB::update('update users set votes = 100 where name = ?', ['John']); 64 | 65 | #### Executando uma consulta Delete 66 | 67 | DB::delete('delete from users'); 68 | 69 | > **Observação:** Os comandos `update` e `delete` retornam o número de linhas afetadas pela operação. 70 | 71 | #### Executando um comando geral 72 | 73 | DB::statement('drop table users'); 74 | 75 | #### "Escutando" eventos de consulta 76 | 77 | Você pode escutar eventos de consultas usando o método `DB::listen`: 78 | 79 | DB::listen(function($sql, $bindings, $time) 80 | { 81 | // 82 | }); 83 | 84 | 85 | ## Transações no banco de dados 86 | 87 | Para executar uma série de operação com uma transação de banco de dados, você pode usar o método `transaction`: 88 | 89 | DB::transaction(function() 90 | { 91 | DB::table('users')->update(['votes' => 1]); 92 | 93 | DB::table('posts')->delete(); 94 | }); 95 | 96 | > **Obsevação:** Qualquer exceção lançada na closure `transaction` irá provocar um rollback na transação automaticamente. 97 | 98 | As vezes, você mesmo pode precisar iniciar a transação: 99 | 100 | DB::beginTransaction(); 101 | 102 | Você pode fazer um rollback na transação usando o método `rollback`: 103 | 104 | DB::rollback(); 105 | 106 | Finalmente, você pode fazer um commit na transação transaction com o método `commit`: 107 | 108 | DB::commit(); 109 | 110 | 111 | ## Acessando conexões 112 | 113 | Quando usar múltiplas conexões, você pode acessá-las com o método `DB::connection`: 114 | 115 | $users = DB::connection('foo')->select(...); 116 | 117 | Você pode acessar diretamente a instância PDO da conexão: 118 | 119 | $pdo = DB::connection()->getPdo(); 120 | 121 | Às vezes você pode precisar se reconectar a um banco de dados: 122 | 123 | DB::reconnect('foo'); 124 | 125 | Se você precisar se desconectar de um banco de dados por ter excedido o limite de instâncias PDO (`max_connections`), use o métoddo `disconnect`: 126 | 127 | DB::disconnect('foo'); 128 | 129 | 130 | ## Logando consultas 131 | 132 | O Laravel pode opcionalmente manter um log na memória de todas as consultas que foram executadas na requisição atual. No entanto, em alguns casos, como por exemplo quando inserndo uma grande quantidade de registros, isso pode fazer com que a aplicação use memória em excesso. Para desabilitar o log, você pode usar o método `disableQueryLog`: 133 | 134 | DB::connection()->enableQueryLog(); 135 | 136 | Para obter um array de consutlas já executadas, você pode usa ro método `getQueryLog`: 137 | 138 | $queries = DB::getQueryLog(); 139 | -------------------------------------------------------------------------------- /documentation.md: -------------------------------------------------------------------------------- 1 | - Prologo 2 | - [Notas da Release](/docs/{{version}}/releases) 3 | - [Guia de atualização](/docs/{{version}}/upgrade) 4 | - [Guia de Contribuições](/docs/{{version}}/contributions) 5 | - Instalação 6 | - [Instalação](/docs/{{version}}/installation) 7 | - [Configuração](/docs/{{version}}/configuration) 8 | - [Homestead](/docs/{{version}}/homestead) 9 | - Básicos 10 | - [Rotas](/docs/{{version}}/routing) 11 | - [Middleware](/docs/{{version}}/middleware) 12 | - [Controladores](/docs/{{version}}/controllers) 13 | - [Requests](/docs/{{version}}/requests) 14 | - [Responses](/docs/{{version}}/responses) 15 | - [Visões](/docs/{{version}}/views) 16 | - Fundações da Arquitetura 17 | - [Service Providers](/docs/{{version}}/providers) 18 | - [Service Container](/docs/{{version}}/container) 19 | - [Contracts](/docs/{{version}}/contracts) 20 | - [Facades](/docs/{{version}}/facades) 21 | - [Ciclo de vida de Request](/docs/{{version}}/lifecycle) 22 | - [Estrutura de aplicação](/docs/{{version}}/structure) 23 | - Serviços 24 | - [Autenticação](/docs/{{version}}/authentication) 25 | - [Faturamento](/docs/{{version}}/billing) 26 | - [Cache](/docs/{{version}}/cache) 27 | - [Coleções](/docs/{{version}}/collections) 28 | - [Command Bus](/docs/{{version}}/bus) 29 | - [Core Extension](/docs/{{version}}/extending) 30 | - [Elixir](/docs/{{version}}/elixir) 31 | - [Encryption](/docs/{{version}}/encryption) 32 | - [Erros & Logging](/docs/{{version}}/errors) 33 | - [Eventos](/docs/{{version}}/events) 34 | - [Filesystem / Armazenamento Cloud](/docs/{{version}}/filesystem) 35 | - [Envoy](/docs/{{version}}/envoy) 36 | - [Hashing](/docs/{{version}}/hashing) 37 | - [Helpers](/docs/{{version}}/helpers) 38 | - [Localização](/docs/{{version}}/localization) 39 | - [Email](/docs/{{version}}/mail) 40 | - [Desenvolvimento de Pacotes](/docs/{{version}}/packages) 41 | - [Paginação](/docs/{{version}}/pagination) 42 | - [Queues](/docs/{{version}}/queues) 43 | - [Session](/docs/{{version}}/session) 44 | - [Templates](/docs/{{version}}/templates) 45 | - [Testes unitários](/docs/{{version}}/testing) 46 | - [Validação](/docs/{{version}}/validation) 47 | - Database 48 | - [Uso básico](/docs/{{version}}/database) 49 | - [Construtor de Query](/docs/{{version}}/queries) 50 | - [Eloquent ORM](/docs/{{version}}/eloquent) 51 | - [Schema Builder](/docs/{{version}}/schema) 52 | - [Migrações & Seeding](/docs/{{version}}/migrations) 53 | - [Redis](/docs/{{version}}/redis) 54 | - Artisan CLI 55 | - [Visão geral](/docs/{{version}}/artisan) 56 | - [Desenvolvimento](/docs/{{version}}/commands) 57 | -------------------------------------------------------------------------------- /encryption.md: -------------------------------------------------------------------------------- 1 | # Encriptação 2 | 3 | - [Introdução](#introduction) 4 | - [Basic Usage](#basic-usage) 5 | 6 | 7 | ## Introdução 8 | 9 | Laravel fornece facildade para uma forte encriptação AES por meio da extenção PHP Mcrypt 10 | 11 | 12 | 13 | ## Uso Básico 14 | 15 | #### Encriptando um Valor 16 | 17 | $encrypted = Crypt::encrypt('secret'); 18 | 19 | 20 | > **Nota:** Certifique-se de setar uma string radomica de 16, 24 , ou 32 caractéres na opção `key` do arquivo, `config/app.php`. Caso contrário, os valores encriptados não estarão seguros. 21 | 22 | 23 | #### Decriptando Valores 24 | 25 | $decrypted = Crypt::decrypt($encryptedValue); 26 | 27 | #### Setando O Modo e o Cipher 28 | 29 | Você pode também setar o cipher e o modo usado pelo ecrypter: 30 | 31 | Crypt::setMode('ctr'); 32 | 33 | Crypt::setCipher($cipher); 34 | -------------------------------------------------------------------------------- /envoy.md: -------------------------------------------------------------------------------- 1 | # Envoy Task Runner 2 | 3 | - [Introdução](#introduction) 4 | - [Instalação](#envoy-installation) 5 | - [Executando Tarefas](#envoy-running-tasks) 6 | - [Múltiplos Servidores](#envoy-multiple-servers) 7 | - [Parallel Execution](#envoy-parallel-execution) 8 | - [Macros de Tarefas](#envoy-task-macros) 9 | - [Notificações](#envoy-notifications) 10 | - [Atualizando o Envoy](#envoy-updating-envoy) 11 | 12 | 13 | ## Introdução 14 | 15 | [Laravel Envoy](https://github.com/laravel/envoy) fornece uma limpa, sintax minimalista por definição tarefas comuns que são executadas nos seus servidores remotos. Usando o estilo de sintax do Blade, você pode facilmente configurar tarefas para deploy, comandos Artisan, e mais. 16 | 17 | > **Nota:** Envoy requere que a versão do PHP seja 5.4 ou superior, e apenas funciona nos sistemas operacionais Mac/Linux. 18 | 19 | 20 | ## Instalação 21 | 22 | Primeiro, instale Envoy usando o comando `global` do Composer: 23 | 24 | composer global require "laravel/envoy=~1.0" 25 | 26 | Assegure-se de alocar o diretório `~/.composer/vendor/bin` na sua variável de ambiente PATH para que então o comando `envoy` seja encontrado quando você executar o comando no terminal. 27 | 28 | Em seguida, crie um arquivo blade `Envoy.blade.php` no diretório raíz do seu projeto. Aqui vai um exemplo de como vocẽ pode começar: 29 | 30 | @servers(['web' => '192.168.1.1']) 31 | 32 | @task('foo', ['on' => 'web']) 33 | ls -la 34 | @endtask 35 | 36 | Como você pode ver, o array de `@servers` é definido no topo do arquivo. Você pode referenciar estes servidores na opção `on` das suas declarações de tarefas. Dentro das suas declarações `@task` você deve alocar o código Bash que irá executar no seu servidor quando a tarefa é executada. 37 | 38 | O comando `init` pode ser usado para criar facilmente um arquivo Stub do Envoy: 39 | 40 | envoy init user@192.168.1.1 41 | 42 | 43 | ## Executando Tarefas 44 | 45 | Para executar tarefas, user o comando `run` da sua instalação Envoy: 46 | 47 | envoy run foo 48 | 49 | Se necessário, você pode passar variáveis no arquivo Envoy usando a linha de comando: 50 | 51 | envoy run deploy --branch=master 52 | 53 | Você pode usar as opções via a sintax do Blade que você está acostumado: 54 | 55 | @servers(['web' => '192.168.1.1']) 56 | 57 | @task('deploy', ['on' => 'web']) 58 | cd site 59 | git pull origin {{ $branch }} 60 | php artisan migrate 61 | @endtask 62 | 63 | #### Bootstrapping 64 | 65 | Você pode usar a diretiva ```@setup``` para declarar variáveis e fazer o trabalho geral do php dentro do arquivo Envoy: 66 | 67 | @setup 68 | $now = new DateTime(); 69 | 70 | $environment = isset($env) ? $env : "testing"; 71 | @endsetup 72 | 73 | Você pode também usar ```@include``` para incluir qualquer arquivo PHP: 74 | 75 | @include('vendor/autoload.php'); 76 | 77 | #### Confirmando Tarefas Antes de Executar 78 | 79 | Se você desejar a confirmação seja exibida na tela uma confirmação, antes que uma tarefa seja executada nos seus servidores, você pode usar a diretiva `confirm`: 80 | 81 | @task('deploy', ['on' => 'web', 'confirm' => true]) 82 | cd site 83 | git pull origin {{ $branch }} 84 | php artisan migrate 85 | @endtask 86 | 87 | 88 | ## Múltiplos Servidores 89 | 90 | Você pode facilmente executar tarefas em múltiplos servidores. Simplesmente liste os servidores na declaração da tarefa: 91 | 92 | @servers(['web-1' => '192.168.1.1', 'web-2' => '192.168.1.2']) 93 | 94 | @task('deploy', ['on' => ['web-1', 'web-2']]) 95 | cd site 96 | git pull origin {{ $branch }} 97 | php artisan migrate 98 | @endtask 99 | 100 | Por padrão, a tarefa será executada em cada servidor em série. Significando, que a tarefa finalizará a execução no primeiro servidor prosseguindo para executar no próximo. 101 | 102 | 103 | ## Execução Paralela 104 | 105 | Se você quiser executar a tarefa em múltiplos servidores em paralelo, simplesmente adicione a opção `parallel` na sua declaração de tarefa: 106 | 107 | @servers(['web-1' => '192.168.1.1', 'web-2' => '192.168.1.2']) 108 | 109 | @task('deploy', ['on' => ['web-1', 'web-2'], 'parallel' => true]) 110 | cd site 111 | git pull origin {{ $branch }} 112 | php artisan migrate 113 | @endtask 114 | 115 | 116 | ## Macros de Tarefas 117 | 118 | Macros permitem que você defina um conjunto de tarefas para serem executadas em sequênia usando um único comando. Por instância: 119 | 120 | @servers(['web' => '192.168.1.1']) 121 | 122 | @macro('deploy') 123 | foo 124 | bar 125 | @endmacro 126 | 127 | @task('foo') 128 | echo "HELLO" 129 | @endtask 130 | 131 | @task('bar') 132 | echo "WORLD" 133 | @endtask 134 | 135 | O macro `deploy` agora pode ser executado por meio um único, e simples comando: 136 | 137 | envoy run deploy 138 | 139 | 140 | 141 | ## Notificações 142 | 143 | #### HipChat 144 | 145 | Depois de executar a tarefa, você pode enviar a notificação para o seu time na sala do HipChat usando uma simples diretiva `@hipchat`: 146 | 147 | @servers(['web' => '192.168.1.1']) 148 | 149 | @task('foo', ['on' => 'web']) 150 | ls -la 151 | @endtask 152 | 153 | @after 154 | @hipchat('token', 'room', 'Envoy') 155 | @endafter 156 | 157 | Você pode também especificar uma mensagem customizada para sua sala no hipchat. Qualquer variável declarada em ```@setup``` ou incluída com ```@include``` será disponibilizada para o uso na mensagem. 158 | 159 | @after 160 | @hipchat('token', 'room', 'Envoy', "$task ran on [$environment]") 161 | @endafter 162 | 163 | Isto é um modo incrivelmente simples de manter seu time notificado sobre as tarefas que estão sendo executadas no servidor. 164 | 165 | #### Slack 166 | 167 | A sintax a seguir pode ser usada para enviar a notificação para o [Slack](https://slack.com): 168 | 169 | @after 170 | @slack('hook', 'channel', 'message') 171 | @endafter 172 | 173 | Você pode recuperar sua URL webhook criando um "WebHooks Entrada" (webhook é um modo que aplicação tem de fornecer a outras aplicações informações real-time) na integração no site do Slack. Por exemplo: 174 | 175 | https://hooks.slack.com/services/ZZZZZZZZZ/YYYYYYYYY/XXXXXXXXXXXXXXX 176 | 177 | Você pode fornecer um dos seguintes para parâmetro do canal: 178 | 179 | - Para enviar a notificação apra o canal: `#channel` 180 | - Para enviar a notificação apra o usuário: `@user` 181 | 182 | Se nenhum argumento do `channel` for fornecido, o canal usará o padrão. 183 | 184 | > Nota: Notificação Slack irão apenas ser enviada se todas as tarefas forem completadas com sucesso. 185 | 186 | 187 | ## Atualizando o Envoy 188 | 189 | Para atualizar o Envoy, simplesmente use o Composer: 190 | 191 | composer global update 192 | 193 | -------------------------------------------------------------------------------- /errors.md: -------------------------------------------------------------------------------- 1 | # Errors & Logging 2 | 3 | - [Configuração](#configuration) 4 | - [Manipulando Erros](#handling-errors) 5 | - [Exceções HTTP](#http-exceptions) 6 | - [Logging](#logging) 7 | 8 | 9 | ## Configuração 10 | 11 | As instalações para sua aplicação são configuradas na classe de inicialização `Illuminate\Foundation\Bootstrap\ConfigureLogging`. Esta classe utiliza as opções de configuração de `log` do seu arquivo de configuração `config/app.php`. 12 | 13 | Por padrão, o log é configurado para usar arquivos de log diários; porém, você pode customizar este comportamento como necessário. Desde que o Laravel usa a popular biblioteca de log [Monolog](https://github.com/Seldaek/monolog), você pode tirar vantagem da variedade de manipuladores que o Monolog Oferece. 14 | 15 | Por exemplo, se você quiser usar um arquivo de log único ao invés de arquivos diários, você pode fazer a seguinte mudança no seu arquivo de configuração `config/app.php`: 16 | 17 | 'log' => 'single' 18 | 19 | De fora da caixa, Laravel suporta os modes de logging `single`, `daily`, `syslog` e `errorlog`. Porém, você é livre para customizar o loggin da sua aplicação como você desejar, apenas sobrescrevendo a classe de inicialização `ConfigureLogging`. 20 | 21 | ### Detalhe de Erro 22 | 23 | A quantidade de detalhes de erros que sua aplicação exibe através do browser é controlada pelas opções de configurações do seu arquivo de configuração `config/app.php`. Por padrão, estas opções de configuração são definidas para respeitar a variável de ambiente `APP_DEBUG`, que é armazenada em seu arquivo `.env`. 24 | 25 | Para o desenvolvimento local, você pode definir a variável de ambiente `APP_DEBUG` para `true`. ** No seu ambiente de produção, este valor deve ser sempre `false`.** 26 | 27 | 28 | ## Manipulando Erros 29 | 30 | Todas exceções são manipuladas pela class `App\Exceptions\Handler`. Esta classe contém dois métodos: `report` e `render`. 31 | 32 | O método `report` é usado para logar exceções ou manda-las para um serviço externo como o [BugSnag](https://bugsnag.com). Por padrão, o método `report` simplesmente passa a exceção para a implementação base na classe pai onde a exceção é logada. Porém, você é livre para logar exceções como quiser. Se você precisar relatar tipos diferentes de exceções de modos diferente, você pode usar o operador de compação do PHP, `instanceof`. 33 | 34 | /** 35 | * Report or log an exception. 36 | * 37 | * This is a great spot to send exceptions to Sentry, Bugsnag, etc. 38 | * 39 | * @param \Exception $e 40 | * @return void 41 | */ 42 | public function report(Exception $e) 43 | { 44 | if ($e instanceof CustomException) 45 | { 46 | // 47 | } 48 | 49 | return parent::report($e); 50 | } 51 | 52 | O método `render` é responsável por converter a exceção em uma reposta HTTP que deve ser enviada de volta ao browser. Por padão, a execeção é passada para a classe básica que gera uma resposta para você. Porém, você é livre para checar tipos de exceção ou retornar a sua própria resposta customizada. 53 | 54 | A propriedade `dontReport` do manipulador de exceções contém um array de tipos exceção que não serão logados. Por padrão, exceções resultantes de erros 404 não são escritas nos seus arquivos de log. Você pode adiciona outros tipos de exceções para este array, conforme necessário. 55 | 56 | 57 | ## Exceções HTTP 58 | 59 | Algumas exceções descrevem os código de erros HTTP do servidor. Por exemplo, isto pode ser um erro 404 "página não encontrada", um "erro não autorizado" (401) ou até mesmo um erro 500 de desenvolvimento. Afim de retornar tal resposta, use os seguintes: 60 | 61 | abort(404); 62 | 63 | Opcionalmente, você pode fornecer a resposta: 64 | 65 | abort(403, 'Unauthorized action.'); 66 | 67 | Este método pode ser usado a qualquer hora durante o siclo de vida da requisição. 68 | 69 | ### Página de erro 404 Customizada 70 | 71 | Para retornar uma view customizada para todos os erros 404, crie um arquivo `resources/views/errors/404.blade.php`. Esta view irá ser servidar em todos os erros 404 gerados pela sua aplicação. 72 | 73 | 74 | ## Logging 75 | 76 | As instalações do loggin do laravel fornecem uma camada simples no top da poderosa biblioteca [Monolog](http://github.com/seldaek/monolog). Por padrão, Laravel é configurado para criar arquivos de log diariamente para sua aplicação que é armazenado no diretório `storage/logs`. Você pode escrever informações no log assim: 77 | 78 | Log::info('This is some useful information.'); 79 | 80 | Log::warning('Something could be going wrong.'); 81 | 82 | Log::error('Something is really going wrong.'); 83 | 84 | 85 | O logger fornece os setes levels de loggin definidos em [RFC 5424](http://tools.ietf.org/html/rfc5424): **debug**, **info**, **notice**, **warning**, **error**, **critical**, e **alert**. 86 | 87 | Um array de dados contextuais pode também ser passado para os métodos de log: 88 | 89 | Log::info('Log message', ['context' => 'Other helpful information']); 90 | 91 | Monolog tem uma variedade adicional de manipuladores que você pode usar para logging. Se você precisar, você pode acessar a instância subjacente do Monolog que está sendo usada pelo Laravel: 92 | 93 | $monolog = Log::getMonolog(); 94 | 95 | Você pode também registrar um evento para pegar todas as mensagens passada para o Log: 96 | 97 | #### Registrando um Listener(Escutador) de Evento de Log 98 | 99 | Log::listen(function($level, $message, $context) 100 | { 101 | // 102 | }); 103 | -------------------------------------------------------------------------------- /events.md: -------------------------------------------------------------------------------- 1 | # Events 2 | 3 | - [Uso Básico](#basic-usage) 4 | - [Manipuladores de Eventos Em Fila](#queued-event-handlers) 5 | - [Assinantes de Eventos](#event-subscribers) 6 | 7 | 8 | ## Uso Básico 9 | 10 | As instalações de eventos do Laravel fornecem uma simples implementação de observer, o que lhe permite inscrever e escutar eventos em sua aplicação. Classes evento são tipicamente armazenada no diretório `app/Events`, enquanto seus manipuladores são armazenados em `app/Handlers/Events`. 11 | 12 | Você pode gerar uma nova classe de evento usando a ferramenta CLI Artisan: 13 | 14 | php artisan make:event PodcastWasPurchased 15 | 16 | #### Subescrevendo Para um Evento 17 | 18 | O `EventServiceProvider` incluído com a sua aplicação Laravel fornece um lugar conveniente para registrar todos os manipuladores de evento. A propriedade `listen` contém um array de todos os eventos (chaves) e seus manipuladores (valores). É claro que, você pode adicionar quantos eventos forem necessários para sua aplicação. Por exemplo, vamos adicionar o nosso `PodcastWasPurchased`: 19 | 20 | /** 21 | * The event handler mappings for the application. 22 | * 23 | * @var array 24 | */ 25 | protected $listen = [ 26 | 'App\Events\PodcastWasPurchased' => [ 27 | 'App\Handlers\Events\EmailPurchaseConfirmation', 28 | ], 29 | ]; 30 | 31 | Para gerar um manipulador para o evento, use o comando CLI Artisan `handler:event`: 32 | 33 | php artisan handler:event EmailPurchaseConfirmation --event=PodcastWasPurchased 34 | 35 | É claro que, executando manualmente os comandos `make:event` e `handler:event` cada vez que você precisar de um manipulado ou evento é complicado. Em vez disso, simplesmente adicione manipuladores e eventos para o seu `EventServiceProvider` e use o comando `event:generate`. Este comando irá gerar quaisquer eventos ou manipuladores que estão listados no seu `EventServiceProvider`: 36 | 37 | php artisan event:generate 38 | 39 | #### Disparando um Evento 40 | 41 | Agora nos estamos prontos para disparar nossos eventos usando a fachada `Event`: 42 | 43 | $response = Event::fire(new PodcastWasPurchased($podcast)); 44 | 45 | O método `fire` retorna um array de respostas que você pode usar para controlar o que acontece depois na sua aplicação. 46 | 47 | Você pode também usar o `event` "helper" para disparar um evento: 48 | 49 | event(new PodcastWasPurchased($podcast)); 50 | 51 | #### Closure Listeners (Escutadores Closure) 52 | 53 | Você pode até ouvir eventos sem criar classes de manipuladores separadas a final de conta. Por exemplo, no método `boot` do seu EventServiceProvider`, você pode fazer o seguinte: 54 | 55 | Event::listen('App\Events\PodcastWasPurchased', function($event) 56 | { 57 | // Handle the event... 58 | }); 59 | 60 | #### Parando a Propagação De um Evento 61 | 62 | Algumas vezes, você pode desejar parar a propagação de um eventos para outrs escutadores. Você pode fazer isto retornando `false` do seu manipulador: 63 | 64 | Event::listen('App\Events\PodcastWasPurchased', function($event) 65 | { 66 | // Handle the event... 67 | 68 | return false; 69 | }); 70 | 71 | 72 | ## Manipuladores de Eventos em Fila. 73 | 74 | Precisando [enfileirar](/docs/{{version}}/queues) um maipulador de eventos ? Isto não pode ser mais fácil. Quando estiver gerando um manipulador, simplesmente use a flag `--queued`: 75 | 76 | php artisan handler:event SendPurchaseConfirmation --event=PodcastWasPurchased --queued 77 | 78 | Isto irá gerar a classe manipuladora que implementa a interface `Illuminate\Contracts\Queue\ShouldBeQueued`. É isto! Agora quando este manipulador é chamado para um evento, isto irá ser enfileirado automaticamente pelo dispachador de eventos. 79 | 80 | Se nenhuma exceção é lançada quando o manipulador é executado pela fila, o trabalho enfileirador será exluído automaticamente depois que isto tiver sido processado. Se você precisar acessar manualmente os métodos `delete` e `release` do trabalho enfileirado, você pode fazê-lo. A trait `Illuminate\Queue\InteractsWithQueue`, que é incluído por padrão nos manipuladores em fila, dá a você acesso para estes métdodos: 81 | 82 | public function handle(PodcastWasPurchased $event) 83 | { 84 | if (true) 85 | { 86 | $this->release(30); 87 | } 88 | } 89 | 90 | Se você tem um manipulador existente que você gostaria de converter para um manipulador em fila, simplesmente adicione a interface `ShouldBeQueued` para a classe manualmente. 91 | 92 | 93 | ## Assinantes de eventos 94 | 95 | #### Definindo um Assinante de evento 96 | 97 | Assinantes de eventos são classes que podem subescrever para múltiplos eventos de dentro da própria classe. Assinantes devem definir o método `subscribe`, que irá ser passado para uma instância de despachador de eventos: 98 | 99 | class UserEventHandler { 100 | 101 | /** 102 | * Handle user login events. 103 | */ 104 | public function onUserLogin($event) 105 | { 106 | // 107 | } 108 | 109 | /** 110 | * Handle user logout events. 111 | */ 112 | public function onUserLogout($event) 113 | { 114 | // 115 | } 116 | 117 | /** 118 | * Register the listeners for the subscriber. 119 | * 120 | * @param Illuminate\Events\Dispatcher $events 121 | * @return array 122 | */ 123 | public function subscribe($events) 124 | { 125 | $events->listen('App\Events\UserLoggedIn', 'UserEventHandler@onUserLogin'); 126 | 127 | $events->listen('App\Events\UserLoggedOut', 'UserEventHandler@onUserLogout'); 128 | } 129 | 130 | } 131 | 132 | #### Registrando um Assinante de Evento 133 | 134 | Uma vez que o assinante tenha sido definido, isto pode ser registrado com a classe `Event`. 135 | 136 | $subscriber = new UserEventHandler; 137 | 138 | Event::subscribe($subscriber); 139 | 140 | Você pode também usar o [container de serviço](/docs/{{version}}/container) para resolver seu assinante. Para fazê-lo, simplesmente passe o nome do seu assinante ppara o método `subscribe`: 141 | 142 | Event::subscribe('UserEventHandler'); 143 | 144 | -------------------------------------------------------------------------------- /filesystem.md: -------------------------------------------------------------------------------- 1 | # Sistema de arquivos / Armazenamento na nuvem 2 | 3 | - [Introdução](#introduction) 4 | - [Configuração](#configuration) 5 | - [Utilização básica](#basic-usage) 6 | - [Custom Filesystems](#custom-filesystems) 7 | 8 | 9 | ## Introdução 10 | 11 | O Laravel provê uma maravilhosa abstração do sistema de arquivos graças ao pacote PHP [Flysystem](https://github.com/thephpleague/flysystem), do Frank de Jonge. A integração "Laravel Flysystem" possibilita uma forma simples para utilizar drivers para trabalhar com sistemas de arquivos locais, Amazon S3, a Rackspace Cloud Storage. Melhor do que isso, é extremamente simples alternar entre essas opções de armazenamento. A API trata cada sistema de armazenamento da mesma forma! 12 | 13 | 14 | ## Configuração 15 | 16 | O arquivo de configuração dos sistema de arquivos está localizado em `config/filesystems.php`. Neste arquivo você pode configurar todos os seus "discos". Cada disco representa um driver de armazenamento particular e o local de armazenamento. No arquivo de configuração você encontra exemplos para cada driver suportado. Então, simplesmente modifique a configuração para refletir as suas preferências e credenciais do seu armazenamento! 17 | 18 | Antes de tilizar os drivers S3 or Rackspace, voCê precisará instalar os devidos pacotes através do Composer: 19 | 20 | - Amazon S3: `league/flysystem-aws-s3-v2 ~1.0` 21 | - Rackspace: `league/flysystem-rackspace ~1.0` 22 | 23 | A propósito, você pode configurar quantos discos você quiser, e pode ter múltiplos discos que usem o mesmo driver. 24 | 25 | Quando utilizando o driver `local`, observe que todas as operações com arquivos são relativas ao diretório `root` definido em seu arquivo de configuração. Por padrão, este valor é configurado no doretório `storage/app`. Portanto, o seguinte método iria armazenar um arquivo em `storage/app/file.txt`: 26 | 27 | Storage::disk('local')->put('file.txt', 'Contents'); 28 | 29 | 30 | ## Utilização básica 31 | 32 | A fachada `Storage` pode ser usada para interagir com qualquer um dos seus discos configurados. Alternativamente, você pode tipar o contrato `Illuminate\Contracts\Filesystem\Factory` em qualquer classe que é resolvida via [container de serviços](/docs/{{version}}/container) do Laravel. 33 | 34 | #### Obtendo um disco específico 35 | 36 | $disk = Storage::disk('s3'); 37 | 38 | $disk = Storage::disk('local'); 39 | 40 | #### Verificando se um arquivo existe 41 | 42 | $exists = Storage::disk('s3')->exists('file.jpg'); 43 | 44 | #### Executando métodos no disco padrão 45 | 46 | if (Storage::exists('file.jpg')) 47 | { 48 | // 49 | } 50 | 51 | #### Obtendo o conteúdo de um arquivo 52 | 53 | $contents = Storage::get('file.jpg'); 54 | 55 | #### Atribuindo o conteúdo a um arquivo 56 | 57 | Storage::put('file.jpg', $contents); 58 | 59 | #### Colocando conteúdo no início de um arquivo (prepend) 60 | 61 | Storage::prepend('file.log', 'Prepended Text'); 62 | 63 | #### Colocando conteúdo no fim de um arquivo (append) 64 | 65 | Storage::append('file.log', 'Appended Text'); 66 | 67 | #### Excluindo um arquivo 68 | 69 | Storage::delete('file.jpg'); 70 | 71 | Storage::delete(['file1.jpg', 'file2.jpg']); 72 | 73 | #### Copiando um arquivo para um novo local 74 | 75 | Storage::copy('old/file1.jpg', 'new/file1.jpg'); 76 | 77 | #### Movendo um arquivo para um novo local 78 | 79 | Storage::move('old/file1.jpg', 'new/file1.jpg'); 80 | 81 | #### Obtendo o tamanho de um arquivo 82 | 83 | $size = Storage::size('file1.jpg'); 84 | 85 | #### Obtendo a data da última nodificação (UNIX) 86 | 87 | $time = Storage::lastModified('file1.jpg'); 88 | 89 | #### Obtendo todos os arquivos de um diretório 90 | 91 | $files = Storage::files($directory); 92 | 93 | // Recursivo... 94 | $files = Storage::allFiles($directory); 95 | 96 | #### Obtendo todos os diretórios de um diretório 97 | 98 | $directories = Storage::directories($directory); 99 | 100 | // Recursivo... 101 | $directories = Storage::allDirectories($directory); 102 | 103 | #### Cria um diretório 104 | 105 | Storage::makeDirectory($directory); 106 | 107 | #### Apaga um diretório 108 | 109 | Storage::deleteDirectory($directory); 110 | 111 | 112 | ## Sistemas de arquivos Customizados 113 | 114 | A integração do sistema de arquivos do Laravel fornece drivers para vários "drivers" de fora da caixa, contudo, sistemas de arquivos não é limitado a esses e tem adaptadores para vários outros sistemas de armazenamento. Você pode criar um driver customizado se você desejar usar um desses adaptadores adicionais nas suas aplicações Laravel. Não se precupe, não é tão difícil. 115 | 116 | A fim de criar o sistema de arquivos você precisará criar um fornecedor de serviços, tais como `DropboxFilesystemServiceProvider`. No método `boot` dos fornecedores, você pode injetar uma instância do contrato `Illuminate\Contracts\Filesystem\Factory` e chamar o método `extend` da instância injetada. Alternativamente, você pode usar o método `extend` da fachada `Disk`. 117 | 118 | O primeiro argumento do método `extend` é o nome do driver e o segundo é uma é uma Closure(função anômima declarada dentro do escopo de outra.) que recebe as variáveis `$app`e `$config`. O resolvedor da Closure deve retornar a instância de `League\Flysystem\Filesystem`. 119 | 120 | > **Nota** A variável $config já irá conter os valores definidos no arquivo `config/filesystems.php` para o disco especificado. 121 | 122 | #### O Examplo do Dropbox 123 | 124 | 7 | ## Introdução 8 | 9 | O facade `Hash` do Laravel, fornece um seguro hash Bcrypt para armazenar senhas de usuários. Se você estiver usando o controller `AuthController` que está incluso na sua aplicação Laravel, ele será responsável por verificar as senhas Bcrypt contra as versões un-hashed fornecidas pelo usuário. 10 | 11 | Da mesma forma, o serviço `Registrar` que vem com o Laravel faz uma chamada apropriada da função `bcrypt` para senhas armazenadas. 12 | 13 | 14 | ## Uso básico 15 | 16 | #### Criando um Hash usando Bcrypt 17 | 18 | $password = Hash::make('secret'); 19 | 20 | Você também pode usar a função helper `bcrypt`; 21 | 22 | $password = bcrypt('secret'); 23 | 24 | #### Verificando uma senha contra um Hash 25 | 26 | if (Hash::check('secret', $hashedPassword)) 27 | { 28 | // As senhas conincidem... 29 | } 30 | 31 | #### Verificando se precisa criar um Hash para a senha 32 | 33 | if (Hash::needsRehash($hashed)) 34 | { 35 | $hashed = Hash::make('secret'); 36 | } 37 | -------------------------------------------------------------------------------- /helpers.md: -------------------------------------------------------------------------------- 1 | # Helper Functions 2 | 3 | - [Arrays](#arrays) 4 | - [Paths](#paths) 5 | - [Routing](#routing) 6 | - [Strings](#strings) 7 | - [URLs](#urls) 8 | - [Miscellaneous](#miscellaneous) 9 | 10 | 11 | ## Arrays 12 | 13 | ### array_add 14 | 15 | The `array_add` function adds a given key / value pair to the array if the given key doesn't already exist in the array. 16 | 17 | $array = ['foo' => 'bar']; 18 | 19 | $array = array_add($array, 'key', 'value'); 20 | 21 | ### array_divide 22 | 23 | The `array_divide` function returns two arrays, one containing the keys, and the other containing the values of the original array. 24 | 25 | $array = ['foo' => 'bar']; 26 | 27 | list($keys, $values) = array_divide($array); 28 | 29 | ### array_dot 30 | 31 | The `array_dot` function flattens a multi-dimensional array into a single level array that uses "dot" notation to indicate depth. 32 | 33 | $array = ['foo' => ['bar' => 'baz']]; 34 | 35 | $array = array_dot($array); 36 | 37 | // ['foo.bar' => 'baz']; 38 | 39 | ### array_except 40 | 41 | The `array_except` method removes the given key / value pairs from the array. 42 | 43 | $array = array_except($array, ['keys', 'to', 'remove']); 44 | 45 | ### array_fetch 46 | 47 | The `array_fetch` method returns a flattened array containing the selected nested element. 48 | 49 | $array = [ 50 | ['developer' => ['name' => 'Taylor']], 51 | ['developer' => ['name' => 'Dayle']] 52 | ]; 53 | 54 | $array = array_fetch($array, 'developer.name'); 55 | 56 | // ['Taylor', 'Dayle']; 57 | 58 | ### array_first 59 | 60 | The `array_first` method returns the first element of an array passing a given truth test. 61 | 62 | $array = [100, 200, 300]; 63 | 64 | $value = array_first($array, function($key, $value) 65 | { 66 | return $value >= 150; 67 | }); 68 | 69 | A default value may also be passed as the third parameter: 70 | 71 | $value = array_first($array, $callback, $default); 72 | 73 | ### array_last 74 | 75 | The `array_last` method returns the last element of an array passing a given truth test. 76 | 77 | $array = [350, 400, 500, 300, 200, 100]; 78 | 79 | $value = array_last($array, function($key, $value) 80 | { 81 | return $value > 350; 82 | }); 83 | 84 | // 500 85 | 86 | A default value may also be passed as the third parameter: 87 | 88 | $value = array_last($array, $callback, $default); 89 | 90 | ### array_flatten 91 | 92 | The `array_flatten` method will flatten a multi-dimensional array into a single level. 93 | 94 | $array = ['name' => 'Joe', 'languages' => ['PHP', 'Ruby']]; 95 | 96 | $array = array_flatten($array); 97 | 98 | // ['Joe', 'PHP', 'Ruby']; 99 | 100 | ### array_forget 101 | 102 | The `array_forget` method will remove a given key / value pair from a deeply nested array using "dot" notation. 103 | 104 | $array = ['names' => ['joe' => ['programmer']]]; 105 | 106 | array_forget($array, 'names.joe'); 107 | 108 | ### array_get 109 | 110 | The `array_get` method will retrieve a given value from a deeply nested array using "dot" notation. 111 | 112 | $array = ['names' => ['joe' => ['programmer']]]; 113 | 114 | $value = array_get($array, 'names.joe'); 115 | 116 | $value = array_get($array, 'names.john', 'default'); 117 | 118 | > **Note:** Want something like `array_get` but for objects instead? Use `object_get`. 119 | 120 | ### array_only 121 | 122 | The `array_only` method will return only the specified key / value pairs from the array. 123 | 124 | $array = ['name' => 'Joe', 'age' => 27, 'votes' => 1]; 125 | 126 | $array = array_only($array, ['name', 'votes']); 127 | 128 | ### array_pluck 129 | 130 | The `array_pluck` method will pluck a list of the given key / value pairs from the array. 131 | 132 | $array = [['name' => 'Taylor'], ['name' => 'Dayle']]; 133 | 134 | $array = array_pluck($array, 'name'); 135 | 136 | // ['Taylor', 'Dayle']; 137 | 138 | ### array_pull 139 | 140 | The `array_pull` method will return a given key / value pair from the array, as well as remove it. 141 | 142 | $array = ['name' => 'Taylor', 'age' => 27]; 143 | 144 | $name = array_pull($array, 'name'); 145 | 146 | ### array_set 147 | 148 | The `array_set` method will set a value within a deeply nested array using "dot" notation. 149 | 150 | $array = ['names' => ['programmer' => 'Joe']]; 151 | 152 | array_set($array, 'names.editor', 'Taylor'); 153 | 154 | ### array_sort 155 | 156 | The `array_sort` method sorts the array by the results of the given Closure. 157 | 158 | $array = [ 159 | ['name' => 'Jill'], 160 | ['name' => 'Barry'] 161 | ]; 162 | 163 | $array = array_values(array_sort($array, function($value) 164 | { 165 | return $value['name']; 166 | })); 167 | 168 | ### array_where 169 | 170 | Filter the array using the given Closure. 171 | 172 | $array = [100, '200', 300, '400', 500]; 173 | 174 | $array = array_where($array, function($key, $value) 175 | { 176 | return is_string($value); 177 | }); 178 | 179 | // Array ( [1] => 200 [3] => 400 ) 180 | 181 | ### head 182 | 183 | Return the first element in the array. 184 | 185 | $first = head($this->returnsArray('foo')); 186 | 187 | ### last 188 | 189 | Return the last element in the array. Useful for method chaining. 190 | 191 | $last = last($this->returnsArray('foo')); 192 | 193 | 194 | ## Paths 195 | 196 | ### app_path 197 | 198 | Get the fully qualified path to the `app` directory. 199 | 200 | $path = app_path(); 201 | 202 | ### base_path 203 | 204 | Get the fully qualified path to the root of the application install. 205 | 206 | ### config_path 207 | 208 | Get the fully qualitifed path to the `config` directory. 209 | 210 | ### public_path 211 | 212 | Get the fully qualified path to the `public` directory. 213 | 214 | ### storage_path 215 | 216 | Get the fully qualified path to the `storage` directory. 217 | 218 | 219 | ## Routing 220 | 221 | ### get 222 | 223 | Register a new GET route with the router. 224 | 225 | get('/', function() { return 'Hello World'; }); 226 | 227 | ### post 228 | 229 | Register a new POST route with the router. 230 | 231 | post('foo/bar', 'FooController@action'); 232 | 233 | ### put 234 | 235 | Register a new PUT route with the router. 236 | 237 | put('foo/bar', 'FooController@action'); 238 | 239 | ### patch 240 | 241 | Register a new PATCH route with the router. 242 | 243 | patch('foo/bar', 'FooController@action'); 244 | 245 | ### delete 246 | 247 | Register a new DELETE route with the router. 248 | 249 | delete('foo/bar', 'FooController@action'); 250 | 251 | ### resource 252 | 253 | Register a new RESTful resource route with the router. 254 | 255 | resource('foo', 'FooController'); 256 | 257 | 258 | ## Strings 259 | 260 | ### camel_case 261 | 262 | Convert the given string to `camelCase`. 263 | 264 | $camel = camel_case('foo_bar'); 265 | 266 | // fooBar 267 | 268 | ### class_basename 269 | 270 | Get the class name of the given class, without any namespace names. 271 | 272 | $class = class_basename('Foo\Bar\Baz'); 273 | 274 | // Baz 275 | 276 | ### e 277 | 278 | Run `htmlentities` over the given string, with UTF-8 support. 279 | 280 | $entities = e('foo'); 281 | 282 | ### ends_with 283 | 284 | Determine if the given haystack ends with a given needle. 285 | 286 | $value = ends_with('This is my name', 'name'); 287 | 288 | ### snake_case 289 | 290 | Convert the given string to `snake_case`. 291 | 292 | $snake = snake_case('fooBar'); 293 | 294 | // foo_bar 295 | 296 | ### str_limit 297 | 298 | Limit the number of characters in a string. 299 | 300 | str_limit($value, $limit = 100, $end = '...') 301 | 302 | Example: 303 | 304 | $value = str_limit('The PHP framework for web artisans.', 7); 305 | 306 | // The PHP... 307 | 308 | ### starts_with 309 | 310 | Determine if the given haystack begins with the given needle. 311 | 312 | $value = starts_with('This is my name', 'This'); 313 | 314 | ### str_contains 315 | 316 | Determine if the given haystack contains the given needle. 317 | 318 | $value = str_contains('This is my name', 'my'); 319 | 320 | ### str_finish 321 | 322 | Add a single instance of the given needle to the haystack. Remove any extra instances. 323 | 324 | $string = str_finish('this/string', '/'); 325 | 326 | // this/string/ 327 | 328 | ### str_is 329 | 330 | Determine if a given string matches a given pattern. Asterisks may be used to indicate wildcards. 331 | 332 | $value = str_is('foo*', 'foobar'); 333 | 334 | ### str_plural 335 | 336 | Convert a string to its plural form (English only). 337 | 338 | $plural = str_plural('car'); 339 | 340 | ### str_random 341 | 342 | Generate a random string of the given length. 343 | 344 | $string = str_random(40); 345 | 346 | ### str_singular 347 | 348 | Convert a string to its singular form (English only). 349 | 350 | $singular = str_singular('cars'); 351 | 352 | ### str_slug 353 | 354 | Generate a URL friendly "slug" from a given string. 355 | 356 | str_slug($title, $separator); 357 | 358 | Example: 359 | 360 | $title = str_slug("Laravel 5 Framework", "-"); 361 | 362 | // laravel-5-framework 363 | 364 | ### studly_case 365 | 366 | Convert the given string to `StudlyCase`. 367 | 368 | $value = studly_case('foo_bar'); 369 | 370 | // FooBar 371 | 372 | ### trans 373 | 374 | Translate a given language line. Alias of `Lang::get`. 375 | 376 | $value = trans('validation.required'): 377 | 378 | ### trans_choice 379 | 380 | Translate a given language line with inflection. Alias of `Lang::choice`. 381 | 382 | $value = trans_choice('foo.bar', $count); 383 | 384 | 385 | ## URLs 386 | 387 | ### action 388 | 389 | Generate a URL for a given controller action. 390 | 391 | $url = action('HomeController@getIndex', $params); 392 | 393 | ### route 394 | 395 | Generate a URL for a given named route. 396 | 397 | $url = route('routeName', $params); 398 | 399 | ### asset 400 | 401 | Generate a URL for an asset. 402 | 403 | $url = asset('img/photo.jpg'); 404 | 405 | ### secure_asset 406 | 407 | Generate a URL for an asset using HTTPS. 408 | 409 | echo secure_asset('foo/bar.zip', $title, $attributes = []); 410 | 411 | ### secure_url 412 | 413 | Generate a fully qualified URL to a given path using HTTPS. 414 | 415 | echo secure_url('foo/bar', $parameters = []); 416 | 417 | ### url 418 | 419 | Generate a fully qualified URL to the given path. 420 | 421 | echo url('foo/bar', $parameters = [], $secure = null); 422 | 423 | 424 | ## Miscellaneous 425 | 426 | ### csrf_token 427 | 428 | Get the value of the current CSRF token. 429 | 430 | $token = csrf_token(); 431 | 432 | ### dd 433 | 434 | Dump the given variable and end execution of the script. 435 | 436 | dd($value); 437 | 438 | ### elixir 439 | 440 | Get the path to a versioned Elixir file. 441 | 442 | elixir($file); 443 | 444 | ### env 445 | 446 | Gets the value of an environment variable or return a default value. 447 | 448 | env('APP_ENV', 'production') 449 | 450 | ### event 451 | 452 | Fire an event. 453 | 454 | event('my.event'); 455 | 456 | ### value 457 | 458 | If the given value is a `Closure`, return the value returned by the `Closure`. Otherwise, return the value. 459 | 460 | $value = value(function() { return 'bar'; }); 461 | 462 | ### view 463 | 464 | Get a View instance for the given view path. 465 | 466 | return view('auth.login'); 467 | 468 | ### with 469 | 470 | Return the given object. 471 | 472 | $value = with(new Foo)->doWork(); 473 | -------------------------------------------------------------------------------- /homestead.md: -------------------------------------------------------------------------------- 1 | # Laravel Homestead 2 | 3 | - [Introduction](#introduction) 4 | - [Included Software](#included-software) 5 | - [Installation & Setup](#installation-and-setup) 6 | - [Daily Usage](#daily-usage) 7 | - [Ports](#ports) 8 | - [Blackfire Profiler](#blackfire-profiler) 9 | 10 | 11 | ## Introduction 12 | 13 | Laravel strives to make the entire PHP development experience delightful, including your local development environment. [Vagrant](http://vagrantup.com) provides a simple, elegant way to manage and provision Virtual Machines. 14 | 15 | Laravel Homestead is an official, pre-packaged Vagrant "box" that provides you a wonderful development environment without requiring you to install PHP, HHVM, a web server, and any other server software on your local machine. No more worrying about messing up your operating system! Vagrant boxes are completely disposable. If something goes wrong, you can destroy and re-create the box in minutes! 16 | 17 | Homestead runs on any Windows, Mac, or Linux system, and includes the Nginx web server, PHP 5.6, MySQL, Postgres, Redis, Memcached, and all of the other goodies you need to develop amazing Laravel applications. 18 | 19 | > **Note:** If you are using Windows, you may need to enable hardware virtualization (VT-x). It can usually be enabled via your BIOS. 20 | 21 | Homestead is currently built and tested using Vagrant 1.7. 22 | 23 | 24 | ## Included Software 25 | 26 | - Ubuntu 14.04 27 | - PHP 5.6 28 | - HHVM 29 | - Nginx 30 | - MySQL 31 | - Postgres 32 | - Node (With Bower, Grunt, and Gulp) 33 | - Redis 34 | - Memcached 35 | - Beanstalkd 36 | - [Laravel Envoy](/docs/{{version}}/envoy) 37 | - [Blackfire Profiler](#blackfire-profiler) 38 | 39 | 40 | ## Installation & Setup 41 | 42 | ### Installing VirtualBox / VMware & Vagrant 43 | 44 | Before launching your Homestead environment, you must install [VirtualBox](https://www.virtualbox.org/wiki/Downloads) and [Vagrant](http://www.vagrantup.com/downloads.html). Both of these software packages provide easy-to-use visual installers for all popular operating systems. 45 | 46 | #### VMware 47 | 48 | In addition to VirtualBox, Homestead also supports VMware. To use the VMware provider, you will need to purchase both VMware Fusion / Desktop and the [VMware Vagrant plug-in](http://www.vagrantup.com/vmware). VMware provides much faster shared folder performance out of the box. 49 | 50 | ### Adding The Vagrant Box 51 | 52 | Once VirtualBox / VMware and Vagrant have been installed, you should add the `laravel/homestead` box to your Vagrant installation using the following command in your terminal. It will take a few minutes to download the box, depending on your Internet connection speed: 53 | 54 | vagrant box add laravel/homestead 55 | 56 | If this command fails, you may have an old version of Vagrant that requires the full URL: 57 | 58 | vagrant box add laravel/homestead https://atlas.hashicorp.com/laravel/boxes/homestead 59 | 60 | ### Installing Homestead 61 | 62 | You may install Homestead manually by simply cloning the repository. Consider cloning the repository into a `Homestead` folder within your "home" directory, as the Homestead box will serve as the host to all of your Laravel (and PHP) projects: 63 | 64 | git clone https://github.com/laravel/homestead.git Homestead 65 | 66 | Once you have cloned the Homestead repository, run the `bash init.sh` command from the Homestead directory to create the `Homestead.yaml` configuration file: 67 | 68 | bash init.sh 69 | 70 | The `Homestead.yaml` file will be placed in your `~/.homestead` directory. 71 | 72 | ### Configure Your Provider 73 | 74 | The `provider` key in your `Homestead.yaml` file indicates which Vagrant provider should be used: `virtualbox` or `vmware_fusion`. You may set this to whichever provider you prefer. 75 | 76 | provider: virtualbox 77 | 78 | ### Set Your SSH Key 79 | 80 | Next, you should edit the `Homestead.yaml` file. In this file, you can configure the path to your public SSH key, as well as the folders you wish to be shared between your main machine and the Homestead virtual machine. 81 | 82 | Don't have an SSH key? On Mac and Linux, you can generally create an SSH key pair using the following command: 83 | 84 | ssh-keygen -t rsa -C "you@homestead" 85 | 86 | On Windows, you may install [Git](http://git-scm.com/) and use the `Git Bash` shell included with Git to issue the command above. Alternatively, you may use [PuTTY](http://www.chiark.greenend.org.uk/~sgtatham/putty/download.html) and [PuTTYgen](http://www.chiark.greenend.org.uk/~sgtatham/putty/download.html). 87 | 88 | Once you have created a SSH key, specify the key's path in the `authorize` property of your `Homestead.yaml` file. 89 | 90 | ### Configure Your Shared Folders 91 | 92 | The `folders` property of the `Homestead.yaml` file lists all of the folders you wish to share with your Homestead environment. As files within these folders are changed, they will be kept in sync between your local machine and the Homestead environment. You may configure as many shared folders as necessary! 93 | 94 | To enable [NFS](http://docs.vagrantup.com/v2/synced-folders/nfs.html), just add a simple flag to your synced folder: 95 | 96 | folders: 97 | - map: ~/Code 98 | to: /home/vagrant/Code 99 | type: "nfs" 100 | 101 | ### Configure Your Nginx Sites 102 | 103 | Not familiar with Nginx? No problem. The `sites` property allows you to easily map a "domain" to a folder on your Homestead environment. A sample site configuration is included in the `Homestead.yaml` file. Again, you may add as many sites to your Homestead environment as necessary. Homestead can serve as a convenient, virtualized environment for every Laravel project you are working on! 104 | 105 | You can make any Homestead site use [HHVM](http://hhvm.com) by setting the `hhvm` option to `true`: 106 | 107 | sites: 108 | - map: homestead.app 109 | to: /home/vagrant/Code/Laravel/public 110 | hhvm: true 111 | 112 | Each site will be accessible by HTTP via port 8000 and HTTPS via port 44300. 113 | 114 | ### Bash Aliases 115 | 116 | To add Bash aliases to your Homestead box, simply add to the `aliases` file in the root of the `~/.homestead` directory. 117 | 118 | ### Launch The Vagrant Box 119 | 120 | Once you have edited the `Homestead.yaml` to your liking, run the `vagrant up` command from your Homestead directory. 121 | 122 | Vagrant will boot the virtual machine, and configure your shared folders and Nginx sites automatically! To destroy the machine, you may use the `vagrant destroy --force` command. 123 | 124 | Don't forget to add the "domains" for your Nginx sites to the `hosts` file on your machine! The `hosts` file will redirect your requests for the local domains into your Homestead environment. On Mac and Linux, this file is located at `/etc/hosts`. On Windows, it is located at `C:\Windows\System32\drivers\etc\hosts`. The lines you add to this file will look like the following: 125 | 126 | 192.168.10.10 homestead.app 127 | 128 | Make sure the IP address listed is the one you set in your `Homestead.yaml` file. Once you have added the domain to your `hosts` file, you can access the site via your web browser! 129 | 130 | http://homestead.app 131 | 132 | To learn how to connect to your databases, read on! 133 | 134 | 135 | ## Daily Usage 136 | 137 | ### Connecting Via SSH 138 | 139 | Since you will probably need to SSH into your Homestead machine frequently, consider creating an "alias" on your host machine to quickly SSH into the Homestead box: 140 | 141 | alias vm="ssh vagrant@127.0.0.1 -p 2222" 142 | 143 | Once you create this alias, you can simply use the "vm" command to SSH into your Homestead machine from anywhere on your system. 144 | 145 | Alternatively, you can use the `vagrant ssh` command from your Homestead directory. 146 | 147 | ### Connecting To Your Databases 148 | 149 | A `homestead` database is configured for both MySQL and Postgres out of the box. For even more convenience, Laravel's `local` database configuration is set to use this database by default. 150 | 151 | To connect to your MySQL or Postgres database from your main machine via Navicat or Sequel Pro, you should connect to `127.0.0.1` and port 33060 (MySQL) or 54320 (Postgres). The username and password for both databases is `homestead` / `secret`. 152 | 153 | > **Note:** You should only use these non-standard ports when connecting to the databases from your main machine. You will use the default 3306 and 5432 ports in your Laravel database configuration file since Laravel is running _within_ the Virtual Machine. 154 | 155 | ### Adding Additional Sites 156 | 157 | Once your Homestead environment is provisioned and running, you may want to add additional Nginx sites for your Laravel applications. You can run as many Laravel installations as you wish on a single Homestead environment. There are two ways to do this: First, you may simply add the sites to your `Homestead.yaml` file and then run `vagrant provision` from your Homestead directory. 158 | 159 | > **Note:** This process is destructive. When running the `provision` command, your existing databases will be destroyed and recreated. 160 | 161 | Alternatively, you may use the `serve` script that is available on your Homestead environment. To use the `serve` script, SSH into your Homestead environment and run the following command: 162 | 163 | serve domain.app /home/vagrant/Code/path/to/public/directory 80 164 | 165 | > **Note:** After running the `serve` command, do not forget to add the new site to the `hosts` file on your main machine! 166 | 167 | 168 | ## Ports 169 | 170 | The following ports are forwarded to your Homestead environment: 171 | 172 | - **SSH:** 2222 → Forwards To 22 173 | - **HTTP:** 8000 → Forwards To 80 174 | - **HTTPS:** 44300 → Forwards To 443 175 | - **MySQL:** 33060 → Forwards To 3306 176 | - **Postgres:** 54320 → Forwards To 5432 177 | 178 | ### Adding Additional Ports 179 | 180 | If you wish, you may forward additional ports to the Vagrant box, as well as specify their protocol: 181 | 182 | ports: 183 | - send: 93000 184 | to: 9300 185 | - send: 7777 186 | to: 777 187 | protocol: udp 188 | 189 | 190 | ## Blackfire Profiler 191 | 192 | [Blackfire Profiler](https://blackfire.io) by SensioLabs automatically gathers data about your code's execution, such as RAM, CPU time, and disk I/O. Homestead makes it a breeze to use this profiler for your own applications. 193 | 194 | All of the proper packages have already been installed on your Homestead box, you simply need to set a Blackfire **Server** ID and token in your `Homestead.yaml` file: 195 | 196 | blackfire: 197 | - id: your-server-id 198 | token: your-server-token 199 | client-id: your-client-id 200 | client-token: your-client-token 201 | 202 | Once you have configured your Blackfire credentials, re-provision the box using `vagrant provision` from your Homestead directory. Of course, be sure to review the [Blackfire documentation](https://blackfire.io/getting-started) to learn how to install the Blackfire companion extension for your web browser. 203 | -------------------------------------------------------------------------------- /installation.md: -------------------------------------------------------------------------------- 1 | # Installation 2 | 3 | - [Install Composer](#install-composer) 4 | - [Install Laravel](#install-laravel) 5 | - [Server Requirements](#server-requirements) 6 | 7 | 8 | ## Install Composer 9 | 10 | Laravel utilizes [Composer](http://getcomposer.org) to manage its dependencies. So, before using Laravel, you will need to make sure you have Composer installed on your machine. 11 | 12 | 13 | ## Install Laravel 14 | 15 | ### Via Laravel Installer 16 | 17 | First, download the Laravel installer using Composer. 18 | 19 | composer global require "laravel/installer=~1.1" 20 | 21 | Make sure to place the `~/.composer/vendor/bin` directory in your PATH so the `laravel` executable can be located by your system. 22 | 23 | Once installed, the simple `laravel new` command will create a fresh Laravel installation in the directory you specify. For instance, `laravel new blog` would create a directory named `blog` containing a fresh Laravel installation with all dependencies installed. This method of installation is much faster than installing via Composer: 24 | 25 | laravel new blog 26 | 27 | ### Via Composer Create-Project 28 | 29 | You may also install Laravel by issuing the Composer `create-project` command in your terminal: 30 | 31 | composer create-project laravel/laravel --prefer-dist 32 | 33 | ### Scaffolding 34 | 35 | Laravel ships with scaffolding for user registration and authentication. If you would like to remove this scaffolding, use the `fresh` Artisan command: 36 | 37 | php artisan fresh 38 | 39 | 40 | ## Server Requirements 41 | 42 | The Laravel framework has a few system requirements: 43 | 44 | - PHP >= 5.4 45 | - Mcrypt PHP Extension 46 | - OpenSSL PHP Extension 47 | - Mbstring PHP Extension 48 | - Tokenizer PHP Extension 49 | 50 | As of PHP 5.5, some OS distributions may require you to manually install the PHP JSON extension. When using Ubuntu, this can be done via `apt-get install php5-json`. 51 | 52 | 53 | ## Configuration 54 | 55 | The first thing you should do after installing Laravel is set your application key to a random string. If you installed Laravel via Composer, this key has probably already been set for you by the `key:generate` command. 56 | 57 | Typically, this string should be 32 characters long. The key can be set in the `.env` environment file. **If the application key is not set, your user sessions and other encrypted data will not be secure!** 58 | 59 | 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. 60 | 61 | Once Laravel is installed, you should also [configure your local environment](/docs/{{version}}/configuration#environment-configuration). 62 | 63 | > **Note:** You should never have the `app.debug` configuration option set to `true` for a production application. 64 | 65 | 66 | ### Permissions 67 | 68 | Laravel may require some permissions to be configured: folders within `storage` and `vendor` require write access by the web server. 69 | 70 | 71 | ## Pretty URLs 72 | 73 | ### Apache 74 | 75 | The framework ships with a `public/.htaccess` file that is used to allow URLs without `index.php`. If you use Apache to serve your Laravel application, be sure to enable the `mod_rewrite` module. 76 | 77 | If the `.htaccess` file that ships with Laravel does not work with your Apache installation, try this one: 78 | 79 | Options +FollowSymLinks 80 | RewriteEngine On 81 | 82 | RewriteCond %{REQUEST_FILENAME} !-d 83 | RewriteCond %{REQUEST_FILENAME} !-f 84 | RewriteRule ^ index.php [L] 85 | 86 | ### Nginx 87 | 88 | On Nginx, the following directive in your site configuration will allow "pretty" URLs: 89 | 90 | location / { 91 | try_files $uri $uri/ /index.php?$query_string; 92 | } 93 | 94 | Of course, when using [Homestead](/docs/{{version}}/homestead), pretty URLs will be configured automatically. 95 | -------------------------------------------------------------------------------- /license.md: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | Copyright © Taylor Otwell 3 | 4 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 5 | 6 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 7 | 8 | THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -------------------------------------------------------------------------------- /lifecycle.md: -------------------------------------------------------------------------------- 1 | # Request Lifecycle 2 | 3 | - [Introduction](#introduction) 4 | - [Lifecycle Overview](#lifecycle-overview) 5 | - [Focus On Service Providers](#focus-on-service-providers) 6 | 7 | 8 | ## Introduction 9 | 10 | When using any tool in the "real world", you feel more confident if you understand how that tool works. Application development is no different. When you understand how your development tools function, you feel more comfortable and confident using them. 11 | 12 | The goal of this document is to give you a good, high-level overview of how the Laravel framework "works". By getting to know the overall framework better, everything feels less "magical" and you will be more confident building your applications. 13 | 14 | If you don't understand all of the terms right away, don't lose heart! Just try to get a basic grasp of what is going on, and your knowledge will grow as you explore other sections of the documentation. 15 | 16 | 17 | ## Lifecycle Overview 18 | 19 | #### First Things 20 | 21 | The entry point for all requests to a Laravel application is the `public/index.php` file. All requests are directed to this file by your web server (Apache / Nginx) configuration. The `index.php` file doesn't contain much code. Rather, it is simply a starting point for loading the rest of the framework. 22 | 23 | The `index.php` file loads the Composer generated autoloader definition, and then retrieves an instance of the Laravel application from `bootstrap/app.php` script. The first action taken by Laravel itself is to create an instance of the application / [service container](/docs/{{version}}/container). 24 | 25 | #### HTTP / Console Kernels 26 | 27 | Next, the incoming request is sent to either the HTTP kernel or the console kernel, depending on the type of request that is entering the application. These two kernels serve as the central location that all requests flow through. For now, let's just focus on the HTTP kernel, which is located in `app/Http/Kernel.php`. 28 | 29 | The HTTP kernel extends the `Illuminate\Foundation\Http\Kernel` class, which defines an array of `bootstrappers` that will be run before the request is executed. These bootstrappers configure error handling, configure logging, detect the application environment, and perform other tasks that need to be done before the request is actually handled. 30 | 31 | The HTTP kernel also defines a list of HTTP [middleware](/docs/{{version}}/middleware) that all requests must pass through before being handled by the application. These middleware handle reading and writing the HTTP session, determine if the application is in maintenance mode, verifying the CSRF token, and more. 32 | 33 | The method signature for the HTTP kernel's `handle` method is quite simple: receive a `Request` and return a `Response`. Think of the Kernel as being a big black box that represents your entire application. Feed it HTTP requests and it will return HTTP responses. 34 | 35 | #### Service Providers 36 | 37 | One of the most important Kernel bootstrapping actions is loading the service providers for your application. All of the service providers for the application are configured in the `config/app.php` configuration file's `providers` array. First, the `register` method will be called on all providers, then, once all providers have been registered, the `boot` method will be called. 38 | 39 | #### Dispatch Request 40 | 41 | Once the application has been bootstrapped and all service providers have been registered, the `Request` will be handed off to the router for dispatching. The router will dispatch the request to a route or controller, as well as run any route specific middleware. 42 | 43 | 44 | ## Focus On Service Providers 45 | 46 | Service providers are truly the key to bootstrapping a Laravel application. The application instance is created, the service providers are registered, and the request is handed to the bootstrapped application. It's really that simple! 47 | 48 | Having a firm grasp of how a Laravel application is built and bootstrapped via service providers is very valuable. Of course, your application's default service providers are stored in the `app/Providers` directory. 49 | 50 | By default, the `AppServiceProvider` is fairly empty. This provider is a great place to add your application's own bootstrapping and service container bindings. Of course, for large applications, you may wish to create several service providers, each with a more granular type of bootstrapping. 51 | -------------------------------------------------------------------------------- /localization.md: -------------------------------------------------------------------------------- 1 | # Localization 2 | 3 | - [Introduction](#introduction) 4 | - [Language Files](#language-files) 5 | - [Basic Usage](#basic-usage) 6 | - [Pluralization](#pluralization) 7 | - [Validation Localization](#validation) 8 | - [Overriding Package Language Files](#overriding-package-language-files) 9 | 10 | 11 | ## Introduction 12 | 13 | The Laravel `Lang` facade provides a convenient way of retrieving strings in various languages, allowing you to easily support multiple languages within your application. 14 | 15 | 16 | ## Language Files 17 | 18 | Language strings are stored in files within the `resources/lang` directory. Within this directory there should be a subdirectory for each language supported by the application. 19 | 20 | /resources 21 | /lang 22 | /en 23 | messages.php 24 | /es 25 | messages.php 26 | 27 | #### Example Language File 28 | 29 | Language files simply return an array of keyed strings. For example: 30 | 31 | 'Welcome to our application' 35 | ]; 36 | 37 | #### Changing The Default Language At Runtime 38 | 39 | The default language for your application is stored in the `config/app.php` configuration file. You may change the active language at any time using the `App::setLocale` method: 40 | 41 | App::setLocale('es'); 42 | 43 | #### Setting The Fallback Language 44 | 45 | You may also configure a "fallback language", which will be used when the active language does not contain a given language line. Like the default language, the fallback language is also configured in the `config/app.php` configuration file: 46 | 47 | 'fallback_locale' => 'en', 48 | 49 | 50 | ## Basic Usage 51 | 52 | #### Retrieving Lines From A Language File 53 | 54 | echo Lang::get('messages.welcome'); 55 | 56 | The first segment of the string passed to the `get` method is the name of the language file, and the second is the name of the line that should be retrieved. 57 | 58 | > **Note:** If a language line does not exist, the key will be returned by the `get` method. 59 | 60 | You may also use the `trans` helper function, which is an alias for the `Lang::get` method. 61 | 62 | echo trans('messages.welcome'); 63 | 64 | #### Making Replacements In Lines 65 | 66 | You may also define place-holders in your language lines: 67 | 68 | 'welcome' => 'Welcome, :name', 69 | 70 | Then, pass a second argument of replacements to the `Lang::get` method: 71 | 72 | echo Lang::get('messages.welcome', ['name' => 'Dayle']); 73 | 74 | #### Determine If A Language File Contains A Line 75 | 76 | if (Lang::has('messages.welcome')) 77 | { 78 | // 79 | } 80 | 81 | 82 | ## Pluralization 83 | 84 | Pluralization is a complex problem, as different languages have a variety of complex rules for pluralization. You may easily manage this in your language files. By using a "pipe" character, you may separate the singular and plural forms of a string: 85 | 86 | 'apples' => 'There is one apple|There are many apples', 87 | 88 | You may then use the `Lang::choice` method to retrieve the line: 89 | 90 | echo Lang::choice('messages.apples', 10); 91 | 92 | You may also supply a locale argument to specify the language. For example, if you want to use the Russian (ru) language: 93 | 94 | echo Lang::choice('товар|товара|товаров', $count, [], 'ru'); 95 | 96 | Since the Laravel translator is powered by the Symfony Translation component, you may also create more explicit pluralization rules easily: 97 | 98 | 'apples' => '{0} There are none|[1,19] There are some|[20,Inf] There are many', 99 | 100 | 101 | 102 | ## Validation 103 | 104 | For localization for validation errors and messages, take a look at the documentation on Validation. 105 | 106 | 107 | ## Overriding Package Language Files 108 | 109 | Many packages ship with their own language lines. Instead of hacking the package's core files to tweak these lines, you may override them by placing files in the `resources/lang/packages/{locale}/{package}` directory. So, for example, if you need to override the English language lines in `messages.php` for a package named `skyrim/hearthfire`, you would place a language file at: `resources/lang/packages/en/hearthfire/messages.php`. In this file you would define only the language lines you wish to override. Any language lines you don't override will still be loaded from the package's language files. 110 | -------------------------------------------------------------------------------- /mail.md: -------------------------------------------------------------------------------- 1 | # Mail 2 | 3 | - [Configuration](#configuration) 4 | - [Basic Usage](#basic-usage) 5 | - [Embedding Inline Attachments](#embedding-inline-attachments) 6 | - [Queueing Mail](#queueing-mail) 7 | - [Mail & Local Development](#mail-and-local-development) 8 | 9 | 10 | ## Configuration 11 | 12 | Laravel provides a clean, simple API over the popular [SwiftMailer](http://swiftmailer.org) library. The mail configuration file is `config/mail.php`, and contains options allowing you to change your SMTP host, port, and credentials, as well as set a global `from` address for all messages delivered by the library. You may use any SMTP server you wish. If you wish to use the PHP `mail` function to send mail, you may change the `driver` to `mail` in the configuration file. A `sendmail` driver is also available. 13 | 14 | ### API Drivers 15 | 16 | Laravel also includes drivers for the Mailgun and Mandrill HTTP APIs. These APIs are often simpler and quicker than the SMTP servers. Both of these drivers require that the Guzzle 5 HTTP library be installed into your application. You can add Guzzle 5 to your project by adding the following line to your `composer.json` file: 17 | 18 | "guzzlehttp/guzzle": "~5.0" 19 | 20 | #### Mailgun Driver 21 | 22 | To use the Mailgun driver, set the `driver` option to `mailgun` in your `config/mail.php` configuration file. Next, create an `config/services.php` configuration file if one does not already exist for your project. Verify that it contains the following options: 23 | 24 | 'mailgun' => [ 25 | 'domain' => 'your-mailgun-domain', 26 | 'secret' => 'your-mailgun-key', 27 | ], 28 | 29 | #### Mandrill Driver 30 | 31 | To use the Mandrill driver, set the `driver` option to `mandrill` in your `config/mail.php` configuration file. Next, create an `config/services.php` configuration file if one does not already exist for your project. Verify that it contains the following options: 32 | 33 | 'mandrill' => [ 34 | 'secret' => 'your-mandrill-key', 35 | ], 36 | 37 | ### Log Driver 38 | 39 | If the `driver` option of your `config/mail.php` configuration file is set to `log`, all e-mails will be written to your log files, and will not actually be sent to any of the recipients. This is primarily useful for quick, local debugging and content verification. 40 | 41 | 42 | ## Basic Usage 43 | 44 | The `Mail::send` method may be used to send an e-mail message: 45 | 46 | Mail::send('emails.welcome', ['key' => 'value'], function($message) 47 | { 48 | $message->to('foo@example.com', 'John Smith')->subject('Welcome!'); 49 | }); 50 | 51 | The first argument passed to the `send` method is the name of the view that should be used as the e-mail body. The second is the data to be passed to the view, often as an associative array where the data items are available to the view by `$key`. The third is a Closure allowing you to specify various options on the e-mail message. 52 | 53 | > **Note:** A `$message` variable is always passed to e-mail views, and allows the inline embedding of attachments. So, it is best to avoid passing a `message` variable in your view payload. 54 | 55 | You may also specify a plain text view to use in addition to an HTML view: 56 | 57 | Mail::send(['html.view', 'text.view'], $data, $callback); 58 | 59 | Or, you may specify only one type of view using the `html` or `text` keys: 60 | 61 | Mail::send(['text' => 'view'], $data, $callback); 62 | 63 | You may specify other options on the e-mail message such as any carbon copies or attachments as well: 64 | 65 | Mail::send('emails.welcome', $data, function($message) 66 | { 67 | $message->from('us@example.com', 'Laravel'); 68 | 69 | $message->to('foo@example.com')->cc('bar@example.com'); 70 | 71 | $message->attach($pathToFile); 72 | }); 73 | 74 | When attaching files to a message, you may also specify a MIME type and / or a display name: 75 | 76 | $message->attach($pathToFile, ['as' => $display, 'mime' => $mime]); 77 | 78 | If you just need to e-mail a simple string instead of an entire view, use the `raw` method: 79 | 80 | Mail::raw('Text to e-mail', function($message) 81 | { 82 | $message->from('us@example.com', 'Laravel'); 83 | 84 | $message->to('foo@example.com')->cc('bar@example.com'); 85 | }); 86 | 87 | > **Note:** The message instance passed to a `Mail::send` Closure extends the SwiftMailer message class, allowing you to call any method on that class to build your e-mail messages. 88 | 89 | 90 | ## Embedding Inline Attachments 91 | 92 | Embedding inline images into your e-mails is typically cumbersome; however, Laravel provides a convenient way to attach images to your e-mails and retrieving the appropriate CID. 93 | 94 | #### Embedding An Image In An E-Mail View 95 | 96 | 97 | Here is an image: 98 | 99 | 100 | 101 | 102 | #### Embedding Raw Data In An E-Mail View 103 | 104 | 105 | Here is an image from raw data: 106 | 107 | 108 | 109 | 110 | Note that the `$message` variable is always passed to e-mail views by the `Mail` facade. 111 | 112 | 113 | ## Queueing Mail 114 | 115 | #### Queueing A Mail Message 116 | 117 | Since sending e-mail messages can drastically lengthen the response time of your application, many developers choose to queue e-mail messages for background sending. Laravel makes this easy using its built-in [unified queue API](/docs/{{version}}/queues). To queue a mail message, simply use the `queue` method on the `Mail` facade: 118 | 119 | Mail::queue('emails.welcome', $data, function($message) 120 | { 121 | $message->to('foo@example.com', 'John Smith')->subject('Welcome!'); 122 | }); 123 | 124 | You may also specify the number of seconds you wish to delay the sending of the mail message using the `later` method: 125 | 126 | Mail::later(5, 'emails.welcome', $data, function($message) 127 | { 128 | $message->to('foo@example.com', 'John Smith')->subject('Welcome!'); 129 | }); 130 | 131 | If you wish to specify a specific queue or "tube" on which to push the message, you may do so using the `queueOn` and `laterOn` methods: 132 | 133 | Mail::queueOn('queue-name', 'emails.welcome', $data, function($message) 134 | { 135 | $message->to('foo@example.com', 'John Smith')->subject('Welcome!'); 136 | }); 137 | 138 | 139 | ## Mail & Local Development 140 | 141 | When developing an application that sends e-mail, it's usually desirable to disable the sending of messages from your local or development environment. To do so, you may either call the `Mail::pretend` method, or set the `pretend` option in the `config/mail.php` configuration file to `true`. When the mailer is in `pretend` mode, messages will be written to your application's log files instead of being sent to the recipient. 142 | 143 | If you would like to actually view the test e-mails, consider using a service like [MailTrap](https://mailtrap.io). 144 | -------------------------------------------------------------------------------- /middleware.md: -------------------------------------------------------------------------------- 1 | # HTTP Middleware 2 | 3 | - [Introduction](#introduction) 4 | - [Defining Middleware](#defining-middleware) 5 | - [Registering Middleware](#registering-middleware) 6 | - [Terminable Middleware](#terminable-middleware) 7 | 8 | 9 | ## Introduction 10 | 11 | HTTP middleware provide a convenient mechanism for filtering HTTP requests entering your application. For example, Laravel includes a middleware that verifies the user of your application is authenticated. If the user is not authenticated, the middleware will redirect the user to the login screen. However, if the user is authenticated, the middleware will allow the request to proceed further into the application. 12 | 13 | Of course, middleware can be written to perform a variety of tasks besides authentication. A CORS middleware might be responsible for adding the proper headers to all responses leaving your application. A logging middleware might log all incoming requests to your application. 14 | 15 | There are several middleware included in the Laravel framework, including middleware for maintenance, authentication, CSRF protection, and more. All of these middleware are located in the `app/Http/Middleware` directory. 16 | 17 | 18 | ## Defining Middleware 19 | 20 | To create a new middleware, use the `make:middleware` Artisan command: 21 | 22 | php artisan make:middleware OldMiddleware 23 | 24 | This command will place a new `OldMiddleware` class within your `app/Http/Middleware` directory. In this middleware, we will only allow access to the route if the supplied `age` is greater than 200. Otherwise, we will redirect the users back to the "home" URI. 25 | 26 | input('age') < 200) 40 | { 41 | return redirect('home'); 42 | } 43 | 44 | return $next($request); 45 | } 46 | 47 | } 48 | 49 | As you can see, if the given `age` is less than `200`, the middleware will return an HTTP redirect to the client; otherwise, the request will be passed further into the application. To pass the request deeper into the application (allowing the middleware to "pass"), simply call the `$next` callback with the `$request`. 50 | 51 | It's best to envision middleware as a series of "layers" HTTP requests must pass through before they hit your application. Each layer can examine the request and even reject it entirely. 52 | 53 | ### *Before* / *After* Middleware 54 | 55 | Whether a middleware runs before or after a request depends on the middleware itself. This middleware would perform some task **before** the request is handled by the application: 56 | 57 | 86 | ## Registering Middleware 87 | 88 | ### Global Middleware 89 | 90 | If you want a middleware to be run during every HTTP request to your application, simply list the middleware class in the `$middleware` property of your `app/Http/Kernel.php` class. 91 | 92 | ### Assigning Middleware To Routes 93 | 94 | If you would like to assign middleware to specific routes, you should first assign the middleware a short-hand key in your `app/Http/Kernel.php` file. By default, the `$routeMiddleware` property of this class contains entries for the middleware included with Laravel. To add your own, simply append it to this list and assign it a key of your choosing. 95 | 96 | Once the middleware has been defined in the HTTP kernel, you may use the `middleware` key in the route options array: 97 | 98 | Route::get('admin/profile', ['middleware' => 'auth', function() 99 | { 100 | // 101 | }]); 102 | 103 | 104 | ## Terminable Middleware 105 | 106 | Sometimes a middleware may need to do some work after the HTTP response has already been sent to the browser. For example, the "session" middleware included with Laravel writes the session data to storage _after_ the response has been sent to the browser. To accomplish this, you may define the middleware as "terminable". 107 | 108 | use Closure; 109 | use Illuminate\Contracts\Routing\TerminableMiddleware; 110 | 111 | class StartSession implements TerminableMiddleware { 112 | 113 | public function handle($request, Closure $next) 114 | { 115 | return $next($request); 116 | } 117 | 118 | public function terminate($request, $response) 119 | { 120 | // Store the session data... 121 | } 122 | 123 | } 124 | 125 | As you can see, in addition to defining a `handle` method, `TerminableMiddleware` define a `terminate` method. This method receives both the request and the response. Once you have defined a terminable middleware, you should add it to the list of global middlewares in your HTTP kernel. 126 | -------------------------------------------------------------------------------- /migrations.md: -------------------------------------------------------------------------------- 1 | # Migrations & Seeding 2 | 3 | - [Introduction](#introduction) 4 | - [Creating Migrations](#creating-migrations) 5 | - [Running Migrations](#running-migrations) 6 | - [Rolling Back Migrations](#rolling-back-migrations) 7 | - [Database Seeding](#database-seeding) 8 | 9 | 10 | ## Introduction 11 | 12 | Migrations are a type of version control for your database. They allow a team to modify the database schema and stay up to date on the current schema state. Migrations are typically paired with the [Schema Builder](/docs/{{version}}/schema) to easily manage your application's schema. 13 | 14 | 15 | ## Creating Migrations 16 | 17 | To create a migration, you may use the `make:migration` command on the Artisan CLI: 18 | 19 | php artisan make:migration create_users_table 20 | 21 | The migration will be placed in your `database/migrations` folder, and will contain a timestamp which allows the framework to determine the order of the migrations. 22 | 23 | The `--table` and `--create` options may also be used to indicate the name of the table, and whether the migration will be creating a new table: 24 | 25 | php artisan make:migration add_votes_to_users_table --table=users 26 | 27 | php artisan make:migration create_users_table --create=users 28 | 29 | 30 | ## Running Migrations 31 | 32 | #### Running All Outstanding Migrations 33 | 34 | php artisan migrate 35 | 36 | > **Note:** If you receive a "class not found" error when running migrations, try running the `composer dump-autoload` command. 37 | 38 | ### Forcing Migrations In Production 39 | 40 | Some migration operations are destructive, meaning they may cause you to lose data. In order to protect you from running these commands against your production database, you will be prompted for confirmation before these commands are executed. To force the commands to run without a prompt, use the `--force` flag: 41 | 42 | php artisan migrate --force 43 | 44 | 45 | ## Rolling Back Migrations 46 | 47 | #### Rollback The Last Migration Operation 48 | 49 | php artisan migrate:rollback 50 | 51 | #### Rollback all migrations 52 | 53 | php artisan migrate:reset 54 | 55 | #### Rollback all migrations and run them all again 56 | 57 | php artisan migrate:refresh 58 | 59 | php artisan migrate:refresh --seed 60 | 61 | 62 | ## Database Seeding 63 | 64 | Laravel also includes a simple way to seed your database with test data using seed classes. All seed classes are stored in `database/seeds`. Seed classes may have any name you wish, but probably should follow some sensible convention, such as `UserTableSeeder`, etc. By default, a `DatabaseSeeder` class is defined for you. From this class, you may use the `call` method to run other seed classes, allowing you to control the seeding order. 65 | 66 | #### Example Database Seed Class 67 | 68 | class DatabaseSeeder extends Seeder { 69 | 70 | public function run() 71 | { 72 | $this->call('UserTableSeeder'); 73 | 74 | $this->command->info('User table seeded!'); 75 | } 76 | 77 | } 78 | 79 | class UserTableSeeder extends Seeder { 80 | 81 | public function run() 82 | { 83 | DB::table('users')->delete(); 84 | 85 | User::create(['email' => 'foo@bar.com']); 86 | } 87 | 88 | } 89 | 90 | To seed your database, you may use the `db:seed` command on the Artisan CLI: 91 | 92 | php artisan db:seed 93 | 94 | 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: 95 | 96 | php artisan db:seed --class=UserTableSeeder 97 | 98 | You may also seed your database using the `migrate:refresh` command, which will also rollback and re-run all of your migrations: 99 | 100 | php artisan migrate:refresh --seed 101 | -------------------------------------------------------------------------------- /packages.md: -------------------------------------------------------------------------------- 1 | # Package Development 2 | 3 | - [Introduction](#introduction) 4 | - [Views](#views) 5 | - [Translations](#translations) 6 | - [Configuration](#configuration) 7 | - [Public Assets](#public-assets) 8 | - [Publishing File Groups](#publishing-file-groups) 9 | - [Routing](#routing) 10 | 11 | 12 | ## Introduction 13 | 14 | Packages are the primary way of adding functionality to Laravel. Packages might be anything from a great way to work with dates like [Carbon](https://github.com/briannesbitt/Carbon), or an entire BDD testing framework like [Behat](https://github.com/Behat/Behat). 15 | 16 | Of course, there are different types of packages. Some packages are stand-alone, meaning they work with any framework, not just Laravel. Both Carbon and Behat are examples of stand-alone packages. Any of these packages may be used with Laravel by simply requesting them in your `composer.json` file. 17 | 18 | On the other hand, other packages are specifically intended for use with Laravel. These packages may have routes, controllers, views, and configuration specifically intended to enhance a Laravel application. This guide primarily covers the development of those that are Laravel specific. 19 | 20 | All Laravel packages are distributed via [Packagist](http://packagist.org) and [Composer](http://getcomposer.org), so learning about these wonderful PHP package distribution tools is essential. 21 | 22 | 23 | ## Views 24 | 25 | Your package's internal structure is entirely up to you; however, typically each package will contain one or more [service providers](/docs/{{version}}/providers). The service provider contains any [service container](/docs/{{version}}/container) bindings, as well as instructions as to where package configuration, views, and translation files are located. 26 | 27 | ### Views 28 | 29 | Package views are typically referenced using a double-colon "namespace" syntax: 30 | 31 | return view('package::view.name'); 32 | 33 | All you need to do is tell Laravel where the views for a given namespace are located. For example, if your package is named "courier", you might add the following to your service provider's `boot` method: 34 | 35 | public function boot() 36 | { 37 | $this->loadViewsFrom(__DIR__.'/path/to/views', 'courier'); 38 | } 39 | 40 | Now you may load your package views using the following syntax: 41 | 42 | return view('courier::view.name'); 43 | 44 | When you use the `loadViewsFrom` method, Laravel actually registers **two** locations for your views: one in the application's `resources/views/vendor` directory and one in the directory you specify. So, using our `courier` example: when requesting a package view, Laravel will first check if a custom version of the view has been provided by the developer in `resources/views/vendor/courier`. Then, if the view has not been customized, Laravel will search the package view directory you specified in your call to `loadViewsFrom`. This makes it easy for end-users to customize / override your package's views. 45 | 46 | #### Publishing Views 47 | 48 | To publish your package's views to the `resources/views/vendor` directory, you should use the `publishes` method from the `boot` method of your service provider: 49 | 50 | public function boot() 51 | { 52 | $this->loadViewsFrom(__DIR__.'/path/to/views', 'courier'); 53 | 54 | $this->publishes([ 55 | __DIR__.'/path/to/views' => base_path('resources/views/vendor/courier'), 56 | ]); 57 | } 58 | 59 | Now, when users of your package execute Laravel's `vendor:publish` command, your views directory will be copied to the specified location. 60 | 61 | If you would like to overwrite existing files, use the `--force` switch: 62 | 63 | php artisan vendor:publish --force 64 | 65 | > **Note:** You may use the `publishes` method to publish **any** type of file to any location you wish. 66 | 67 | 68 | ## Translations 69 | 70 | Package translation files are typically referenced using a double-colon syntax: 71 | 72 | return trans('package::file.line'); 73 | 74 | All you need to do is tell Laravel where the translations for a given namespace are located. For example, if your package is named "courier", you might add the following to your service provider's `boot` method: 75 | 76 | public function boot() 77 | { 78 | $this->loadTranslationsFrom(__DIR__.'/path/to/translations', 'courier'); 79 | } 80 | 81 | Note that within your `translations` folder, you would have further directories for each language, such as `en`, `es`, `ru`, etc. 82 | 83 | Now you may load your package translations using the following syntax: 84 | 85 | return trans('courier::file.line'); 86 | 87 | 88 | ## Configuration 89 | 90 | Typically, you will want to publish your package's configuration file to the application's own `config` directory. This will allow users of your package to easily override your default configuration options. 91 | 92 | To publish a configuration file, just use the `publishes` method from the `boot` method of your service provider: 93 | 94 | $this->publishes([ 95 | __DIR__.'/path/to/config/courier.php' => config_path('courier.php'), 96 | ]); 97 | 98 | Now, when users of your package execute Laravel's `vendor:publish` command, your file will be copied to the specified location. Of course, once your configuration has been published, it can be accessed like any other configuration file: 99 | 100 | $value = config('courier.option'); 101 | 102 | You may also choose to merge your own package configuration file with the application's copy. This allows your users to include only the options they actually want to override in the published copy of the configuration. To merge the configurations, use the `mergeConfigFrom` method within your service provider's `register` method: 103 | 104 | $this->mergeConfigFrom( 105 | __DIR__.'/path/to/config/courier.php', 'courier' 106 | ); 107 | 108 | 109 | ## Public Assets 110 | 111 | Your packages may have assets such as JavaScript, CSS, and images. To publish assets, use the `publishes` method from your service provider's `boot` method. In this example, we will also add a "public" asset group tag. 112 | 113 | $this->publishes([ 114 | __DIR__.'/path/to/assets' => public_path('vendor/courier'), 115 | ], 'public'); 116 | 117 | Now, when your package's users execute the `vendor:publish` command, your files will be copied to the specified location. Since you typically will need to overwrite the assets every time the package is updated, you may use the `--force` flag: 118 | 119 | php artisan vendor:publish --tag=public --force 120 | 121 | If you would like to make sure your public assets are always up-to-date, you can add this command to the `post-update-cmd` list in your `composer.json` file. 122 | 123 | 124 | ## Publishing File Groups 125 | 126 | You may want to publish groups of files separately. For instance, you might want your users to be able to publish your package's configuration files and asset files separately. You can do this by 'tagging' them: 127 | 128 | // Publish a config file 129 | $this->publishes([ 130 | __DIR__.'/../config/package.php' => config_path('package.php') 131 | ], 'config'); 132 | 133 | // Publish your migrations 134 | $this->publishes([ 135 | __DIR__.'/../database/migrations/' => database_path('/migrations') 136 | ], 'migrations'); 137 | 138 | You can then publish these files separately by referencing their tag like so: 139 | 140 | php artisan vendor:publish --provider="Vendor\Providers\PackageServiceProvider" --tag="config" 141 | 142 | 143 | ## Routing 144 | 145 | To load a routes file for your package, simply `include` it from within your service provider's `boot` method. 146 | 147 | #### Including A Routes File From A Service Provider 148 | 149 | public function boot() 150 | { 151 | include __DIR__.'/../../routes.php'; 152 | } 153 | 154 | > **Note:** If your package is using controllers, you will need to make sure they are properly configured in your `composer.json` file's auto-load section. 155 | -------------------------------------------------------------------------------- /pagination.md: -------------------------------------------------------------------------------- 1 | # Pagination 2 | 3 | - [Configuration](#configuration) 4 | - [Usage](#usage) 5 | - [Appending To Pagination Links](#appending-to-pagination-links) 6 | - [Converting To JSON](#converting-to-json) 7 | 8 | 9 | ## Configuration 10 | 11 | In other frameworks, pagination can be very painful. Laravel makes it a breeze. Laravel can generate an intelligent "range" of links based on the current page. The generated HTML is compatible with the Bootstrap CSS framework. 12 | 13 | 14 | ## Usage 15 | 16 | There are several ways to paginate items. The simplest is by using the `paginate` method on the query builder or an Eloquent model. 17 | 18 | #### Paginating Database Results 19 | 20 | $users = DB::table('users')->paginate(15); 21 | 22 | > **Note:** Currently, pagination operations that use a `groupBy` statement cannot be executed efficiently by Laravel. If you need to use a `groupBy` with a paginated result set, it is recommended that you query the database and create a paginator manually. 23 | 24 | #### Creating A Paginator Manually 25 | 26 | Sometimes you may wish to create a pagination instance manually, passing it an array of items. You may do so by creating either an `Illuminate\Pagination\Paginator` or `Illuminate\Pagination\LengthAwarePaginator` instance, depending on your needs. 27 | 28 | #### Paginating An Eloquent Model 29 | 30 | You may also paginate [Eloquent](/docs/{{version}}/eloquent) models: 31 | 32 | $allUsers = User::paginate(15); 33 | 34 | $someUsers = User::where('votes', '>', 100)->paginate(15); 35 | 36 | The argument passed to the `paginate` method is the number of items you wish to display per page. Once you have retrieved the results, you may display them on your view, and create the pagination links using the `render` method: 37 | 38 |
39 | 40 | name; ?> 41 | 42 |
43 | 44 | render(); ?> 45 | 46 | This is all it takes to create a pagination system! Note that we did not have to inform the framework of the current page. Laravel will determine this for you automatically. 47 | 48 | You may also access additional pagination information via the following methods: 49 | 50 | - `currentPage` 51 | - `lastPage` 52 | - `perPage` 53 | - `hasMorePages` 54 | - `url` 55 | - `nextPageUrl` 56 | - `total` 57 | - `count` 58 | 59 | #### "Simple Pagination" 60 | 61 | If you are only showing "Next" and "Previous" links in your pagination view, you have the option of using the `simplePaginate` method to perform a more efficient query. This is useful for larger datasets when you do not require the display of exact page numbers on your view: 62 | 63 | $someUsers = User::where('votes', '>', 100)->simplePaginate(15); 64 | 65 | #### Customizing The Paginator URI 66 | 67 | You may also customize the URI used by the paginator via the `setPath` method: 68 | 69 | $users = User::paginate(); 70 | 71 | $users->setPath('custom/url'); 72 | 73 | The example above will create URLs like the following: http://example.com/custom/url?page=2 74 | 75 | 76 | ## Appending To Pagination Links 77 | 78 | You can add to the query string of pagination links using the `appends` method on the Paginator: 79 | 80 | appends(['sort' => 'votes'])->render(); ?> 81 | 82 | This will generate URLs that look something like this: 83 | 84 | http://example.com/something?page=2&sort=votes 85 | 86 | If you wish to append a "hash fragment" to the paginator's URLs, you may use the `fragment` method: 87 | 88 | fragment('foo')->render(); ?> 89 | 90 | This method call will generate URLs that look something like this: 91 | 92 | http://example.com/something?page=2#foo 93 | 94 | 95 | ## Converting To JSON 96 | 97 | The `Paginator` class implements the `Illuminate\Contracts\Support\JsonableInterface` contract and exposes the `toJson` method. You may also convert a `Paginator` instance to JSON by returning it from a route. The JSON'd form of the instance will include some "meta" information such as `total`, `current_page`, and `last_page`. The instance's data will be available via the `data` key in the JSON array. 98 | -------------------------------------------------------------------------------- /providers.md: -------------------------------------------------------------------------------- 1 | # Service Providers 2 | 3 | - [Introduction](#introduction) 4 | - [Basic Provider Example](#basic-provider-example) 5 | - [Registering Providers](#registering-providers) 6 | - [Deferred Providers](#deferred-providers) 7 | 8 | 9 | ## Introduction 10 | 11 | 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. 12 | 13 | But, what do we mean by "bootstrapped"? In general, we mean **registering** things, including registering service container bindings, event listeners, filters, and even routes. Service providers are the central place to configure your application. 14 | 15 | If you open the `config/app.php` file included with Laravel, you will see a `providers` array. These are all of the service provider classes that will be loaded for your application. Of course, many of them are "deferred" providers, meaning they will not be loaded on every request, but only when the services they provide are actually needed. 16 | 17 | In this overview you will learn how to write your own service providers and register them with your Laravel application. 18 | 19 | 20 | ## Basic Provider Example 21 | 22 | All service providers extend the `Illuminate\Support\ServiceProvider` class. This abstract class requires that you define at least one method on your provider: `register`. Within the `register` method, you should **only bind things into the [service container](/docs/{{version}}/container)**. You should never attempt to register any event listeners, routes, or any other piece of functionality within the `register` method. 23 | 24 | The Artisan CLI can easily generate a new provider via the `make:provider` command: 25 | 26 | php artisan make:provider RiakServiceProvider 27 | 28 | ### The Register Method 29 | 30 | Now, let's take a look at a basic service provider: 31 | 32 | app->singleton('Riak\Contracts\Connection', function($app) 47 | { 48 | return new Connection($app['config']['riak']); 49 | }); 50 | } 51 | 52 | } 53 | 54 | This service provider only defines a `register` method, and uses that method to define an implementation of `Riak\Contracts\Connection` in the service container. If you don't understand how the service container works, don't worry, [we'll cover that soon](/docs/{{version}}/container). 55 | 56 | This class is namespaced under `App\Providers` since that is the default location for service providers in Laravel. However, you are free to change this as you wish. Your service providers may be placed anywhere that Composer can autoload them. 57 | 58 | ### The Boot Method 59 | 60 | So, what if we need to register an event listener 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. 61 | 62 | listen('SomeEvent', 'SomeEventHandler'); 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 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\AppServiceProvider', 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 | To defer the loading of a provider, set the `defer` property to `true` and define a `provides` method. The `provides` method returns the service container bindings that the provider registers: 119 | 120 | app->singleton('Riak\Contracts\Connection', function($app) 142 | { 143 | return new Connection($app['config']['riak']); 144 | }); 145 | } 146 | 147 | /** 148 | * Get the services provided by the provider. 149 | * 150 | * @return array 151 | */ 152 | public function provides() 153 | { 154 | return ['Riak\Contracts\Connection']; 155 | } 156 | 157 | } 158 | 159 | 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. 160 | -------------------------------------------------------------------------------- /queries.md: -------------------------------------------------------------------------------- 1 | # Query Builder 2 | 3 | - [Introduction](#introduction) 4 | - [Selects](#selects) 5 | - [Joins](#joins) 6 | - [Advanced Wheres](#advanced-wheres) 7 | - [Aggregates](#aggregates) 8 | - [Raw Expressions](#raw-expressions) 9 | - [Inserts](#inserts) 10 | - [Updates](#updates) 11 | - [Deletes](#deletes) 12 | - [Unions](#unions) 13 | - [Pessimistic Locking](#pessimistic-locking) 14 | 15 | 16 | ## Introduction 17 | 18 | The database query builder provides a convenient, fluent interface to creating and running database queries. It can be used to perform most database operations in your application, and works on all supported database systems. 19 | 20 | > **Note:** The Laravel query builder uses PDO parameter binding throughout to protect your application against SQL injection attacks. There is no need to clean strings being passed as bindings. 21 | 22 | 23 | ## Selects 24 | 25 | #### Retrieving All Rows From A Table 26 | 27 | $users = DB::table('users')->get(); 28 | 29 | foreach ($users as $user) 30 | { 31 | var_dump($user->name); 32 | } 33 | 34 | #### Chunking Results From A Table 35 | 36 | DB::table('users')->chunk(100, function($users) 37 | { 38 | foreach ($users as $user) 39 | { 40 | // 41 | } 42 | }); 43 | 44 | You may stop further chunks from being processed by returning `false` from the `Closure`: 45 | 46 | DB::table('users')->chunk(100, function($users) 47 | { 48 | // 49 | 50 | return false; 51 | }); 52 | 53 | #### Retrieving A Single Row From A Table 54 | 55 | $user = DB::table('users')->where('name', 'John')->first(); 56 | 57 | var_dump($user->name); 58 | 59 | #### Retrieving A Single Column From A Row 60 | 61 | $name = DB::table('users')->where('name', 'John')->pluck('name'); 62 | 63 | #### Retrieving A List Of Column Values 64 | 65 | $roles = DB::table('roles')->lists('title'); 66 | 67 | This method will return an array of role titles. You may also specify a custom key column for the returned array: 68 | 69 | $roles = DB::table('roles')->lists('title', 'name'); 70 | 71 | #### Specifying A Select Clause 72 | 73 | $users = DB::table('users')->select('name', 'email')->get(); 74 | 75 | $users = DB::table('users')->distinct()->get(); 76 | 77 | $users = DB::table('users')->select('name as user_name')->get(); 78 | 79 | #### Adding A Select Clause To An Existing Query 80 | 81 | $query = DB::table('users')->select('name'); 82 | 83 | $users = $query->addSelect('age')->get(); 84 | 85 | #### Using Where Operators 86 | 87 | $users = DB::table('users')->where('votes', '>', 100)->get(); 88 | 89 | #### Or Statements 90 | 91 | $users = DB::table('users') 92 | ->where('votes', '>', 100) 93 | ->orWhere('name', 'John') 94 | ->get(); 95 | 96 | #### Using Where Between 97 | 98 | $users = DB::table('users') 99 | ->whereBetween('votes', [1, 100])->get(); 100 | 101 | #### Using Where Not Between 102 | 103 | $users = DB::table('users') 104 | ->whereNotBetween('votes', [1, 100])->get(); 105 | 106 | #### Using Where In With An Array 107 | 108 | $users = DB::table('users') 109 | ->whereIn('id', [1, 2, 3])->get(); 110 | 111 | $users = DB::table('users') 112 | ->whereNotIn('id', [1, 2, 3])->get(); 113 | 114 | #### Using Where Null To Find Records With Unset Values 115 | 116 | $users = DB::table('users') 117 | ->whereNull('updated_at')->get(); 118 | 119 | #### Dynamic Where Clauses 120 | 121 | You may even use "dynamic" where statements to fluently build where statements using magic methods: 122 | 123 | $admin = DB::table('users')->whereId(1)->first(); 124 | 125 | $john = DB::table('users') 126 | ->whereIdAndEmail(2, 'john@doe.com') 127 | ->first(); 128 | 129 | $jane = DB::table('users') 130 | ->whereNameOrAge('Jane', 22) 131 | ->first(); 132 | 133 | #### Order By, Group By, And Having 134 | 135 | $users = DB::table('users') 136 | ->orderBy('name', 'desc') 137 | ->groupBy('count') 138 | ->having('count', '>', 100) 139 | ->get(); 140 | 141 | #### Offset & Limit 142 | 143 | $users = DB::table('users')->skip(10)->take(5)->get(); 144 | 145 | 146 | ## Joins 147 | 148 | The query builder may also be used to write join statements. Take a look at the following examples: 149 | 150 | #### Basic Join Statement 151 | 152 | DB::table('users') 153 | ->join('contacts', 'users.id', '=', 'contacts.user_id') 154 | ->join('orders', 'users.id', '=', 'orders.user_id') 155 | ->select('users.id', 'contacts.phone', 'orders.price') 156 | ->get(); 157 | 158 | #### Left Join Statement 159 | 160 | DB::table('users') 161 | ->leftJoin('posts', 'users.id', '=', 'posts.user_id') 162 | ->get(); 163 | 164 | You may also specify more advanced join clauses: 165 | 166 | DB::table('users') 167 | ->join('contacts', function($join) 168 | { 169 | $join->on('users.id', '=', 'contacts.user_id')->orOn(...); 170 | }) 171 | ->get(); 172 | 173 | If you would like to use a "where" style clause on your joins, you may use the `where` and `orWhere` methods on a join. Instead of comparing two columns, these methods will compare the column against a value: 174 | 175 | DB::table('users') 176 | ->join('contacts', function($join) 177 | { 178 | $join->on('users.id', '=', 'contacts.user_id') 179 | ->where('contacts.user_id', '>', 5); 180 | }) 181 | ->get(); 182 | 183 | 184 | ## Advanced Wheres 185 | 186 | #### Parameter Grouping 187 | 188 | Sometimes you may need to create more advanced where clauses such as "where exists" or nested parameter groupings. The Laravel query builder can handle these as well: 189 | 190 | DB::table('users') 191 | ->where('name', '=', 'John') 192 | ->orWhere(function($query) 193 | { 194 | $query->where('votes', '>', 100) 195 | ->where('title', '<>', 'Admin'); 196 | }) 197 | ->get(); 198 | 199 | The query above will produce the following SQL: 200 | 201 | select * from users where name = 'John' or (votes > 100 and title <> 'Admin') 202 | 203 | #### Exists Statements 204 | 205 | DB::table('users') 206 | ->whereExists(function($query) 207 | { 208 | $query->select(DB::raw(1)) 209 | ->from('orders') 210 | ->whereRaw('orders.user_id = users.id'); 211 | }) 212 | ->get(); 213 | 214 | The query above will produce the following SQL: 215 | 216 | select * from users 217 | where exists ( 218 | select 1 from orders where orders.user_id = users.id 219 | ) 220 | 221 | 222 | ## Aggregates 223 | 224 | The query builder also provides a variety of aggregate methods, such as `count`, `max`, `min`, `avg`, and `sum`. 225 | 226 | #### Using Aggregate Methods 227 | 228 | $users = DB::table('users')->count(); 229 | 230 | $price = DB::table('orders')->max('price'); 231 | 232 | $price = DB::table('orders')->min('price'); 233 | 234 | $price = DB::table('orders')->avg('price'); 235 | 236 | $total = DB::table('users')->sum('votes'); 237 | 238 | 239 | ## Raw Expressions 240 | 241 | Sometimes you may need to use a raw expression in a query. These expressions will be injected into the query as strings, so be careful not to create any SQL injection points! To create a raw expression, you may use the `DB::raw` method: 242 | 243 | #### Using A Raw Expression 244 | 245 | $users = DB::table('users') 246 | ->select(DB::raw('count(*) as user_count, status')) 247 | ->where('status', '<>', 1) 248 | ->groupBy('status') 249 | ->get(); 250 | 251 | 252 | ## Inserts 253 | 254 | #### Inserting Records Into A Table 255 | 256 | DB::table('users')->insert( 257 | ['email' => 'john@example.com', 'votes' => 0] 258 | ); 259 | 260 | #### Inserting Records Into A Table With An Auto-Incrementing ID 261 | 262 | If the table has an auto-incrementing id, use `insertGetId` to insert a record and retrieve the id: 263 | 264 | $id = DB::table('users')->insertGetId( 265 | ['email' => 'john@example.com', 'votes' => 0] 266 | ); 267 | 268 | > **Note:** When using PostgreSQL the insertGetId method expects the auto-incrementing column to be named "id". 269 | 270 | #### Inserting Multiple Records Into A Table 271 | 272 | DB::table('users')->insert([ 273 | ['email' => 'taylor@example.com', 'votes' => 0], 274 | ['email' => 'dayle@example.com', 'votes' => 0] 275 | ]); 276 | 277 | 278 | ## Updates 279 | 280 | #### Updating Records In A Table 281 | 282 | DB::table('users') 283 | ->where('id', 1) 284 | ->update(['votes' => 1]); 285 | 286 | #### Incrementing or decrementing a value of a column 287 | 288 | DB::table('users')->increment('votes'); 289 | 290 | DB::table('users')->increment('votes', 5); 291 | 292 | DB::table('users')->decrement('votes'); 293 | 294 | DB::table('users')->decrement('votes', 5); 295 | 296 | You may also specify additional columns to update: 297 | 298 | DB::table('users')->increment('votes', 1, ['name' => 'John']); 299 | 300 | 301 | ## Deletes 302 | 303 | #### Deleting Records In A Table 304 | 305 | DB::table('users')->where('votes', '<', 100)->delete(); 306 | 307 | #### Deleting All Records From A Table 308 | 309 | DB::table('users')->delete(); 310 | 311 | #### Truncating A Table 312 | 313 | DB::table('users')->truncate(); 314 | 315 | 316 | ## Unions 317 | 318 | The query builder also provides a quick way to "union" two queries together: 319 | 320 | $first = DB::table('users')->whereNull('first_name'); 321 | 322 | $users = DB::table('users')->whereNull('last_name')->union($first)->get(); 323 | 324 | The `unionAll` method is also available, and has the same method signature as `union`. 325 | 326 | 327 | ## Pessimistic Locking 328 | 329 | The query builder includes a few functions to help you do "pessimistic locking" on your SELECT statements. 330 | 331 | To run the SELECT statement with a "shared lock", you may use the `sharedLock` method on a query: 332 | 333 | DB::table('users')->where('votes', '>', 100)->sharedLock()->get(); 334 | 335 | To "lock for update" on a SELECT statement, you may use the `lockForUpdate` method on a query: 336 | 337 | DB::table('users')->where('votes', '>', 100)->lockForUpdate()->get(); 338 | -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 | # Laravel Documentation In Brazilian Portuguese 2 | 3 | ## Contribution Guidelines 4 | 5 | Se a documentação que você pretende submeter é para a versão 5.0 do Laravel, então sua submissão deverá ser para branch 5.0. A Após a verificação e revisão do documento será mergiada com a branch Master. 6 | 7 | Lembrando que este repositório é um trabalho colaborativo para comunidade brasileira de Laravel, não há nenhuma garantia de que esta documentação será oficialializada pela equipe do laravel. 8 | -------------------------------------------------------------------------------- /redis.md: -------------------------------------------------------------------------------- 1 | # Redis 2 | 3 | - [Introduction](#introduction) 4 | - [Configuration](#configuration) 5 | - [Usage](#usage) 6 | - [Pipelining](#pipelining) 7 | 8 | 9 | ## Introduction 10 | 11 | [Redis](http://redis.io) is an open source, advanced key-value store. It is often referred to as a data structure server since keys can contain [strings](http://redis.io/topics/data-types#strings), [hashes](http://redis.io/topics/data-types#hashes), [lists](http://redis.io/topics/data-types#lists), [sets](http://redis.io/topics/data-types#sets), and [sorted sets](http://redis.io/topics/data-types#sorted-sets). 12 | 13 | Before using Redis with Laravel, you will need to install the `predis/predis` package (~1.0) via Composer. 14 | 15 | > **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. 16 | 17 | 18 | ## Configuration 19 | 20 | The Redis configuration for your application is stored in the `config/database.php` file. Within this file, you will see a `redis` array containing the Redis servers used by your application: 21 | 22 | 'redis' => [ 23 | 24 | 'cluster' => true, 25 | 26 | 'default' => ['host' => '127.0.0.1', 'port' => 6379], 27 | 28 | ], 29 | 30 | The default server configuration should suffice for development. However, you are free to modify this array based on your environment. Simply give each Redis server a name, and specify the host and port used by the server. 31 | 32 | The `cluster` option will tell the Laravel Redis client to perform client-side sharding across your Redis nodes, allowing you to pool nodes and create a large amount of available RAM. However, note that client-side sharding does not handle failover; therefore, is primarily suited for cached data that is available from another primary data store. 33 | 34 | If your Redis server requires authentication, you may supply a password by adding a `password` key / value pair to your Redis server configuration array. 35 | 36 | 37 | ## Usage 38 | 39 | You may get a Redis instance by calling the `Redis::connection` method: 40 | 41 | $redis = Redis::connection(); 42 | 43 | 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: 44 | 45 | $redis = Redis::connection('other'); 46 | 47 | Once you have an instance of the Redis client, we may issue any of the [Redis commands](http://redis.io/commands) to the instance. Laravel uses magic methods to pass the commands to the Redis server: 48 | 49 | $redis->set('name', 'Taylor'); 50 | 51 | $name = $redis->get('name'); 52 | 53 | $values = $redis->lrange('names', 5, 10); 54 | 55 | Notice the arguments to the command are simply passed into the magic method. Of course, you are not required to use the magic methods, you may also pass commands to the server using the `command` method: 56 | 57 | $values = $redis->command('lrange', [5, 10]); 58 | 59 | When you are simply executing commands against the default connection, just use static magic methods on the `Redis` class: 60 | 61 | Redis::set('name', 'Taylor'); 62 | 63 | $name = Redis::get('name'); 64 | 65 | $values = Redis::lrange('names', 5, 10); 66 | 67 | > **Note:** Redis [cache](/docs/{{version}}/cache) and [session](/docs/{{version}}/session) drivers are included with Laravel. 68 | 69 | 70 | ## Pipelining 71 | 72 | Pipelining should be used when you need to send many commands to the server in one operation. To get started, use the `pipeline` command: 73 | 74 | #### Piping Many Commands To Your Servers 75 | 76 | Redis::pipeline(function($pipe) 77 | { 78 | for ($i = 0; $i < 1000; $i++) 79 | { 80 | $pipe->set("key:$i", $i); 81 | } 82 | }); 83 | -------------------------------------------------------------------------------- /requests.md: -------------------------------------------------------------------------------- 1 | # HTTP Requests 2 | 3 | - [Obtaining A Request Instance](#obtaining-a-request-instance) 4 | - [Retrieving Input](#retrieving-input) 5 | - [Old Input](#old-input) 6 | - [Cookies](#cookies) 7 | - [Files](#files) 8 | - [Other Request Information](#other-request-information) 9 | 10 | 11 | ## Obtaining A Request Instance 12 | 13 | ### Via Facade 14 | 15 | The `Request` facade will grant you access to the current request that is bound in the container. For example: 16 | 17 | $name = Request::input('name'); 18 | 19 | Remember, if you are in a namespace, you will have to import the `Request` facade using a `use Request;` statement at the top of your class file. 20 | 21 | ### Via Dependency Injection 22 | 23 | To obtain an instance of the current HTTP request via dependency injection, you should type-hint the class on your controller constructor or method. The current request instance will automatically be injected by the [service container](/docs/{{version}}/container): 24 | 25 | input('name'); 41 | 42 | // 43 | } 44 | 45 | } 46 | 47 | If your controller method is also expecting input from a route parameter, simply list your route arguments after your other dependencies: 48 | 49 | 71 | ## Retrieving Input 72 | 73 | #### Retrieving An Input Value 74 | 75 | Using a few simple methods, you may access all user input from your `Illuminate\Http\Request` instance. You do not need to worry about the HTTP verb used for the request, as input is accessed in the same way for all verbs. 76 | 77 | $name = Request::input('name'); 78 | 79 | #### Retrieving A Default Value If The Input Value Is Absent 80 | 81 | $name = Request::input('name', 'Sally'); 82 | 83 | #### Determining If An Input Value Is Present 84 | 85 | if (Request::has('name')) 86 | { 87 | // 88 | } 89 | 90 | #### Getting All Input For The Request 91 | 92 | $input = Request::all(); 93 | 94 | #### Getting Only Some Of The Request Input 95 | 96 | $input = Request::only('username', 'password'); 97 | 98 | $input = Request::except('credit_card'); 99 | 100 | When working on forms with "array" inputs, you may use dot notation to access the arrays: 101 | 102 | $input = Request::input('products.0.name'); 103 | 104 | 105 | ## Old Input 106 | 107 | Laravel also allows you to keep input from one request during the next request. For example, you may need to re-populate a form after checking it for validation errors. 108 | 109 | #### Flashing Input To The Session 110 | 111 | The `flash` method will flash the current input to the [session](/docs/{{version}}/session) so that it is available during the user's next request to the application: 112 | 113 | Request::flash(); 114 | 115 | #### Flashing Only Some Input To The Session 116 | 117 | Request::flashOnly('username', 'email'); 118 | 119 | Request::flashExcept('password'); 120 | 121 | #### Flash & Redirect 122 | 123 | Since you often will want to flash input in association with a redirect to the previous page, you may easily chain input flashing onto a redirect. 124 | 125 | return redirect('form')->withInput(); 126 | 127 | return redirect('form')->withInput(Request::except('password')); 128 | 129 | #### Retrieving Old Data 130 | 131 | To retrieve flashed input from the previous request, use the `old` method on the `Request` instance. 132 | 133 | $username = Request::old('username'); 134 | 135 | If you are displaying old input within a Blade template, it is more convenient to use the `old` helper: 136 | 137 | {{ old('username') }} 138 | 139 | 140 | ## Cookies 141 | 142 | All cookies created by the Laravel framework are encrypted and signed with an authentication code, meaning they will be considered invalid if they have been changed by the client. 143 | 144 | #### Retrieving A Cookie Value 145 | 146 | $value = Request::cookie('name'); 147 | 148 | #### Attaching A New Cookie To A Response 149 | 150 | The `cookie` helper serves as a simple factory for generating new `Symfony\Component\HttpFoundation\Cookie` instances. The cookies may be attached to a `Response` instance using the `withCookie` method: 151 | 152 | $response = new Illuminate\Http\Response('Hello World'); 153 | 154 | $response->withCookie(cookie('name', 'value', $minutes)); 155 | 156 | #### Creating A Cookie That Lasts Forever* 157 | 158 | _By "forever", we really mean five years._ 159 | 160 | $response->withCookie(cookie()->forever('name', 'value')); 161 | 162 | #### Queueing Cookies 163 | 164 | You may also "queue" a cookie to be added to the outgoing response, even before that response has been created: 165 | 166 | 187 | ## Files 188 | 189 | #### Retrieving An Uploaded File 190 | 191 | $file = Request::file('photo'); 192 | 193 | #### Determining If A File Was Uploaded 194 | 195 | if (Request::hasFile('photo')) 196 | { 197 | // 198 | } 199 | 200 | The object returned by the `file` method is an instance of the `Symfony\Component\HttpFoundation\File\UploadedFile` class, which extends the PHP `SplFileInfo` class and provides a variety of methods for interacting with the file. 201 | 202 | #### Determining If An Uploaded File Is Valid 203 | 204 | if (Request::file('photo')->isValid()) 205 | { 206 | // 207 | } 208 | 209 | #### Moving An Uploaded File 210 | 211 | Request::file('photo')->move($destinationPath); 212 | 213 | Request::file('photo')->move($destinationPath, $fileName); 214 | 215 | ### Other File Methods 216 | 217 | There are a variety of other methods available on `UploadedFile` instances. Check out the [API documentation for the class](http://api.symfony.com/2.5/Symfony/Component/HttpFoundation/File/UploadedFile.html) for more information regarding these methods. 218 | 219 | 220 | ## Other Request Information 221 | 222 | The `Request` class provides many methods for examining the HTTP request for your application and extends the `Symfony\Component\HttpFoundation\Request` class. Here are some of the highlights. 223 | 224 | #### Retrieving The Request URI 225 | 226 | $uri = Request::path(); 227 | 228 | #### Retrieving The Request Method 229 | 230 | $method = Request::method(); 231 | 232 | if (Request::isMethod('post')) 233 | { 234 | // 235 | } 236 | 237 | #### Determining If The Request Path Matches A Pattern 238 | 239 | if (Request::is('admin/*')) 240 | { 241 | // 242 | } 243 | 244 | #### Get The Current Request URL 245 | 246 | $url = Request::url(); 247 | -------------------------------------------------------------------------------- /responses.md: -------------------------------------------------------------------------------- 1 | # HTTP Responses 2 | 3 | - [Basic Responses](#basic-responses) 4 | - [Redirects](#redirects) 5 | - [Other Responses](#other-responses) 6 | - [Response Macros](#response-macros) 7 | 8 | 9 | ## Basic Responses 10 | 11 | #### Returning Strings From Routes 12 | 13 | The most basic response from a Laravel route is a string: 14 | 15 | Route::get('/', function() 16 | { 17 | return 'Hello World'; 18 | }); 19 | 20 | #### Creating Custom Responses 21 | 22 | However, for most routes and controller actions, you will be returning a full `Illuminate\Http\Response` instance or a [view](/docs/{{version}}/views). Returning a full `Response` instance allows you to customize the response's HTTP status code and headers. A `Response` instance inherits from the `Symfony\Component\HttpFoundation\Response` class, providing a variety of methods for building HTTP responses: 23 | 24 | use Illuminate\Http\Response; 25 | 26 | return (new Response($content, $status)) 27 | ->header('Content-Type', $value); 28 | 29 | For convenience, you may also use the `response` helper: 30 | 31 | return response($content, $status) 32 | ->header('Content-Type', $value); 33 | 34 | > **Note:** For a full list of available `Response` methods, check out its [API documentation](http://laravel.com/api/master/Illuminate/Http/Response.html) and the [Symfony API documentation](http://api.symfony.com/2.5/Symfony/Component/HttpFoundation/Response.html). 35 | 36 | #### Sending A View In A Response 37 | 38 | If you need access to the `Response` class methods, but want to return a view as the response content, you may use the `view` method for convenience: 39 | 40 | return response()->view('hello')->header('Content-Type', $type); 41 | 42 | #### Attaching Cookies To Responses 43 | 44 | return response($content)->withCookie(cookie('name', 'value')); 45 | 46 | #### Method Chaining 47 | 48 | Keep in mind that most `Response` methods are chainable, allowing for the fluent building of responses: 49 | 50 | return response()->view('hello')->header('Content-Type', $type) 51 | ->withCookie(cookie('name', 'value')); 52 | 53 | 54 | ## Redirects 55 | 56 | Redirect responses are typically instances of the `Illuminate\Http\RedirectResponse` class, and contain the proper headers needed to redirect the user to another URL. 57 | 58 | #### Returning A Redirect 59 | 60 | There are several ways to generate a `RedirectResponse` instance. The simplest method is to use the `redirect` helper method. When testing, it is not common to mock the creation of a redirect response, so using the helper method is almost always acceptable: 61 | 62 | return redirect('user/login'); 63 | 64 | #### Returning A Redirect With Flash Data 65 | 66 | Redirecting to a new URL and [flashing data to the session](/docs/{{version}}/session) are typically done at the same time. So, for convenience, you may create a `RedirectResponse` instance **and** flash data to the session in a single method chain: 67 | 68 | return redirect('user/login')->with('message', 'Login Failed'); 69 | 70 | #### Redirecting To The Previous URL 71 | 72 | You may wish to redirect the user to their previous location, for example, after a form submission. You can do so by using the `back` method: 73 | 74 | return redirect()->back(); 75 | 76 | return redirect()->back()->withInput(); 77 | 78 | #### Returning A Redirect To A Named Route 79 | 80 | 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: 81 | 82 | return redirect()->route('login'); 83 | 84 | #### Returning A Redirect To A Named Route With Parameters 85 | 86 | If your route has parameters, you may pass them as the second argument to the `route` method. 87 | 88 | // For a route with the following URI: profile/{id} 89 | 90 | return redirect()->route('profile', [1]); 91 | 92 | 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: 93 | 94 | return redirect()->route('profile', [$user]); 95 | 96 | #### Returning A Redirect To A Named Route Using Named Parameters 97 | 98 | // For a route with the following URI: profile/{user} 99 | 100 | return redirect()->route('profile', ['user' => 1]); 101 | 102 | #### Returning A Redirect To A Controller Action 103 | 104 | Similarly to generating `RedirectResponse` instances to named routes, you may also generate redirects to [controller actions](/docs/{{version}}/controllers): 105 | 106 | return redirect()->action('App\Http\Controllers\HomeController@index'); 107 | 108 | > **Note:** You do not need to specify the full namespace to the controller if you have registered a root controller namespace via `URL::setRootControllerNamespace`. 109 | 110 | #### Returning A Redirect To A Controller Action With Parameters 111 | 112 | return redirect()->action('App\Http\Controllers\UserController@profile', [1]); 113 | 114 | #### Returning A Redirect To A Controller Action Using Named Parameters 115 | 116 | return redirect()->action('App\Http\Controllers\UserController@profile', ['user' => 1]); 117 | 118 | 119 | ## Other Responses 120 | 121 | The `response` helper may be used to conveniently generate other types of response instances. When the `response` helper is called without arguments, an implementation of the `Illuminate\Contracts\Routing\ResponseFactory` [contract](/docs/{{version}}/contracts) is returned. This contract provides several helpful methods for generating responses. 122 | 123 | #### Creating A JSON Response 124 | 125 | The `json` method will automatically set the `Content-Type` header to `application/json`: 126 | 127 | return response()->json(['name' => 'Abigail', 'state' => 'CA']); 128 | 129 | #### Creating A JSONP Response 130 | 131 | return response()->json(['name' => 'Abigail', 'state' => 'CA']) 132 | ->setCallback($request->input('callback')); 133 | 134 | #### Creating A File Download Response 135 | 136 | return response()->download($pathToFile); 137 | 138 | return response()->download($pathToFile, $name, $headers); 139 | 140 | return response()->download($pathToFile)->deleteFileAfterSend(true); 141 | 142 | > **Note:** Symfony HttpFoundation, which manages file downloads, requires the file being downloaded to have an ASCII file name. 143 | 144 | 145 | ## Response Macros 146 | 147 | If you would like to define a custom response that you can re-use in a variety of your routes and controllers, you may use the `macro` method on an implementation of `Illuminate\Contracts\Routing\ResponseFactory`. 148 | 149 | For example, from a [service provider's](/docs/{{version}}/providers) `boot` method: 150 | 151 | caps('foo'); 176 | -------------------------------------------------------------------------------- /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', ['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->jsonb('options');` | JSONB equivalent to the table 79 | `$table->longText('description');` | LONGTEXT equivalent to the table 80 | `$table->mediumInteger('numbers');` | MEDIUMINT equivalent to the table 81 | `$table->mediumText('description');` | MEDIUMTEXT equivalent to the table 82 | `$table->morphs('taggable');` | Adds INTEGER `taggable_id` and STRING `taggable_type` 83 | `$table->nullableTimestamps();` | Same as `timestamps()`, except allows NULLs 84 | `$table->smallInteger('votes');` | SMALLINT equivalent to the table 85 | `$table->tinyInteger('numbers');` | TINYINT equivalent to the table 86 | `$table->softDeletes();` | Adds **deleted\_at** column for soft deletes 87 | `$table->string('email');` | VARCHAR equivalent column 88 | `$table->string('name', 100);` | VARCHAR equivalent with a length 89 | `$table->text('description');` | TEXT equivalent to the table 90 | `$table->time('sunrise');` | TIME equivalent to the table 91 | `$table->timestamp('added_on');` | TIMESTAMP equivalent to the table 92 | `$table->timestamps();` | Adds **created\_at** and **updated\_at** columns 93 | `$table->rememberToken();` | Adds `remember_token` as VARCHAR(100) NULL 94 | `->nullable()` | Designate that the column allows NULL values 95 | `->default($value)` | Declare a default value for a column 96 | `->unsigned()` | Set INTEGER to UNSIGNED 97 | 98 | #### Using After On MySQL 99 | 100 | If you are using the MySQL database, you may use the `after` method to specify the order of columns: 101 | 102 | $table->string('name')->after('email'); 103 | 104 | 105 | ## Changing Columns 106 | 107 | **Note:** Before changing a column, be sure to add the `doctrine/dbal` dependency to your `composer.json` file. 108 | 109 | 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: 110 | 111 | Schema::table('users', function($table) 112 | { 113 | $table->string('name', 50)->change(); 114 | }); 115 | 116 | We could also modify a column to be nullable: 117 | 118 | Schema::table('users', function($table) 119 | { 120 | $table->string('name', 50)->nullable()->change(); 121 | }); 122 | 123 | 124 | ## Renaming Columns 125 | 126 | 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. 127 | 128 | Schema::table('users', function($table) 129 | { 130 | $table->renameColumn('from', 'to'); 131 | }); 132 | 133 | > **Note:** Renaming columns in a table with `enum` column is currently not supported. 134 | 135 | 136 | ## Dropping Columns 137 | 138 | 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. 139 | 140 | #### Dropping A Column From A Database Table 141 | 142 | Schema::table('users', function($table) 143 | { 144 | $table->dropColumn('votes'); 145 | }); 146 | 147 | #### Dropping Multiple Columns From A Database Table 148 | 149 | Schema::table('users', function($table) 150 | { 151 | $table->dropColumn(['votes', 'avatar', 'location']); 152 | }); 153 | 154 | 155 | ## Checking Existence 156 | 157 | #### Checking For Existence Of Table 158 | 159 | You may easily check for the existence of a table or column using the `hasTable` and `hasColumn` methods: 160 | 161 | if (Schema::hasTable('users')) 162 | { 163 | // 164 | } 165 | 166 | #### Checking For Existence Of Columns 167 | 168 | if (Schema::hasColumn('users', 'email')) 169 | { 170 | // 171 | } 172 | 173 | 174 | ## Adding Indexes 175 | 176 | 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: 177 | 178 | $table->string('email')->unique(); 179 | 180 | Or, you may choose to add the indexes on separate lines. Below is a list of all available index types: 181 | 182 | Command | Description 183 | ------------- | ------------- 184 | `$table->primary('id');` | Adding a primary key 185 | `$table->primary(['first', 'last']);` | Adding composite keys 186 | `$table->unique('email');` | Adding a unique index 187 | `$table->index('state');` | Adding a basic index 188 | 189 | 190 | ## Foreign Keys 191 | 192 | Laravel also provides support for adding foreign key constraints to your tables: 193 | 194 | $table->integer('user_id')->unsigned(); 195 | $table->foreign('user_id')->references('id')->on('users'); 196 | 197 | 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! 198 | 199 | You may also specify options for the "on delete" and "on update" actions of the constraint: 200 | 201 | $table->foreign('user_id') 202 | ->references('id')->on('users') 203 | ->onDelete('cascade'); 204 | 205 | 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: 206 | 207 | $table->dropForeign('posts_user_id_foreign'); 208 | 209 | > **Note:** When creating a foreign key that references an incrementing integer, remember to always make the foreign key column `unsigned`. 210 | 211 | 212 | ## Dropping Indexes 213 | 214 | 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: 215 | 216 | Command | Description 217 | ------------- | ------------- 218 | `$table->dropPrimary('users_id_primary');` | Dropping a primary key from the "users" table 219 | `$table->dropUnique('users_email_unique');` | Dropping a unique index from the "users" table 220 | `$table->dropIndex('geo_state_index');` | Dropping a basic index from the "geo" table 221 | 222 | 223 | ## Dropping Timestamps & SoftDeletes 224 | 225 | To drop the `timestamps`, `nullableTimestamps` or `softDeletes` column types, you may use the following methods: 226 | 227 | Command | Description 228 | ------------- | ------------- 229 | `$table->dropTimestamps();` | Dropping the **created\_at** and **updated\_at** columns from the table 230 | `$table->dropSoftDeletes();` | Dropping **deleted\_at** column from the table 231 | 232 | 233 | ## Storage Engines 234 | 235 | To set the storage engine for a table, set the `engine` property on the schema builder: 236 | 237 | Schema::create('users', function($table) 238 | { 239 | $table->engine = 'InnoDB'; 240 | 241 | $table->string('email'); 242 | }); 243 | -------------------------------------------------------------------------------- /session.md: -------------------------------------------------------------------------------- 1 | # Session 2 | 3 | - [Configuration](#configuration) 4 | - [Session Usage](#session-usage) 5 | - [Flash Data](#flash-data) 6 | - [Database Sessions](#database-sessions) 7 | - [Session Drivers](#session-drivers) 8 | 9 | 10 | ## Configuration 11 | 12 | Since HTTP driven applications are stateless, sessions provide a way to store information about the user across requests. Laravel ships with a variety of session back-ends available for use through a clean, unified API. Support for popular back-ends such as [Memcached](http://memcached.org), [Redis](http://redis.io), and databases is included out of the box. 13 | 14 | The session configuration is stored in `config/session.php`. Be sure to review the well documented options available to you in this file. By default, Laravel is configured to use the `file` session driver, which will work well for the majority of applications. 15 | 16 | Before using Redis sessions with Laravel, you will need to install the `predis/predis` package (~1.0) via Composer. 17 | 18 | > **Note:** If you need all stored session data to be encrypted, set the `encrypt` configuration option to `true`. 19 | 20 | > **Note:** When using the `cookie` session driver, you should **never** remove the `EncryptCookie` middleware from your HTTP kernel. If you remove this middleware, your application will be vulnerable to remote code injection. 21 | 22 | #### Reserved Keys 23 | 24 | The Laravel framework uses the `flash` session key internally, so you should not add an item to the session by that name. 25 | 26 | 27 | ## Session Usage 28 | 29 | The session may be accessed in several ways, via the HTTP request's `session` method, the `Session` facade, or the `session` helper function. When the `session` helper is called without arguments, it will return the entire session object. For example: 30 | 31 | session()->regenerate(); 32 | 33 | #### Storing An Item In The Session 34 | 35 | Session::put('key', 'value'); 36 | 37 | session(['key' => 'value']); 38 | 39 | #### Push A Value Onto An Array Session Value 40 | 41 | Session::push('user.teams', 'developers'); 42 | 43 | #### Retrieving An Item From The Session 44 | 45 | $value = Session::get('key'); 46 | 47 | $value = session('key'); 48 | 49 | #### Retrieving An Item Or Returning A Default Value 50 | 51 | $value = Session::get('key', 'default'); 52 | 53 | $value = Session::get('key', function() { return 'default'; }); 54 | 55 | #### Retrieving An Item And Forgetting It 56 | 57 | $value = Session::pull('key', 'default'); 58 | 59 | #### Retrieving All Data From The Session 60 | 61 | $data = Session::all(); 62 | 63 | #### Determining If An Item Exists In The Session 64 | 65 | if (Session::has('users')) 66 | { 67 | // 68 | } 69 | 70 | #### Removing An Item From The Session 71 | 72 | Session::forget('key'); 73 | 74 | #### Removing All Items From The Session 75 | 76 | Session::flush(); 77 | 78 | #### Regenerating The Session ID 79 | 80 | Session::regenerate(); 81 | 82 | 83 | ## Flash Data 84 | 85 | Sometimes you may wish to store items in the session only for the next request. You may do so using the `Session::flash` method: 86 | 87 | Session::flash('key', 'value'); 88 | 89 | #### Reflashing The Current Flash Data For Another Request 90 | 91 | Session::reflash(); 92 | 93 | #### Reflashing Only A Subset Of Flash Data 94 | 95 | Session::keep(['username', 'email']); 96 | 97 | 98 | ## Database Sessions 99 | 100 | When using the `database` session driver, you will need to setup a table to contain the session items. Below is an example `Schema` declaration for the table: 101 | 102 | Schema::create('sessions', function($table) 103 | { 104 | $table->string('id')->unique(); 105 | $table->text('payload'); 106 | $table->integer('last_activity'); 107 | }); 108 | 109 | Of course, you may use the `session:table` Artisan command to generate this migration for you! 110 | 111 | php artisan session:table 112 | 113 | composer dump-autoload 114 | 115 | php artisan migrate 116 | 117 | 118 | ## Session Drivers 119 | 120 | The session "driver" defines where session data will be stored for each request. Laravel ships with several great drivers out of the box: 121 | 122 | - `file` - sessions will be stored in `storage/framework/sessions`. 123 | - `cookie` - sessions will be stored in secure, encrypted cookies. 124 | - `database` - sessions will be stored in a database used by your application. 125 | - `memcached` / `redis` - sessions will be stored in one of these fast, cached based stores. 126 | - `array` - sessions will be stored in a simple PHP array and will not be persisted across requests. 127 | 128 | > **Note:** The array driver is typically used for running [unit tests](/docs/{{version}}/testing), so no session data will be persisted. 129 | -------------------------------------------------------------------------------- /structure.md: -------------------------------------------------------------------------------- 1 | # Application Structure 2 | 3 | - [Introduction](#introduction) 4 | - [The Root Directory](#the-root-directory) 5 | - [The App Directory](#the-app-directory) 6 | - [Namespacing Your Application](#namespacing-your-application) 7 | 8 | 9 | ## Introduction 10 | 11 | The default Laravel application structure is intended to provide a great starting point for both large and small applications. Of course, you are free to organize your application however you like. Laravel imposes almost no restrictions on where any given class is located - as long as Composer can autoload the class. 12 | 13 | 14 | ## The Root Directory 15 | 16 | The root directory of a fresh Laravel installation contains a variety of folders: 17 | 18 | The `app` directory, as you might expect, contains the core code of your application. We'll explore this folder in more detail soon. 19 | 20 | The `bootstrap` folder contains a few files that bootstrap the framework and configure autoloading. 21 | 22 | The `config` directory, as the name implies, contains all of your application's configuration files. 23 | 24 | The `database` folder contains your database migration and seeds. 25 | 26 | The `public` directory contains the front controller and your assets (images, JavaScript, CSS, etc.). 27 | 28 | The `resources` directory contains your views, raw assets (LESS, SASS, CoffeeScript), and "language" files. 29 | 30 | The `storage` directory contains compiled Blade templates, file based sessions, file caches, and other files generated by the framework. 31 | 32 | The `tests` directory contains your automated tests. 33 | 34 | The `vendor` directory contains your Composer dependencies. 35 | 36 | 37 | ## The App Directory 38 | 39 | The "meat" of your application lives in the `app` directory. By default, this directory is namespaced under `App` and is autoloaded by Composer using the [PSR-4 autoloading standard](http://www.php-fig.org/psr/psr-4/). **You may change this namespace using the `app:name` Artisan command**. 40 | 41 | The `app` directory ships with a variety of additional directories such as `Console`, `Http`, and `Providers`. Think of the `Console` and `Http` directories as providing an API into the "core" of your application. The HTTP protocol and CLI are both mechanisms to interact with your application, but do not actually contain application logic. In other words, they are simply two ways of issuing commands to your application. The `Console` directory contains all of your Artisan commands, while the `Http` directory contains your controllers, filters, and requests. 42 | 43 | The `Commands` directory, of course, houses the commands for your application. Commands represent jobs that can be queued by your application, as well as tasks that you can run synchronously within the current request lifecycle. 44 | 45 | The `Events` directory, as you might expect, houses event classes. Of course, using classes to represent events is not required; however, if you choose to use them, this directory is the default location they will be created by the Artisan command line. 46 | 47 | The `Handlers` directory contains the handler classes for both commands and events. Handlers receive a command or event and perform logic in response to that command or event being fired. 48 | 49 | The `Services` directory contains various "helper" services your application needs to function. For example, the `Registrar` service included with Laravel is responsible for validating and creating new users of your application. Other examples might be services to interact with external APIs, metrics systems, or even services that aggregate data from your own application. 50 | 51 | The `Exceptions` directory contains your application's exception handler and is also a good place to stick any exceptions thrown by your application. 52 | 53 | > **Note:** Many of the classes in the `app` directory can be generated by Artisan via commands. To review the available commands, run the `php artisan list make` command in your terminal. 54 | 55 | 56 | ## Namespacing Your Application 57 | 58 | As discussed above, the default application namespace is `App`; however, you may change this namespace to match the name of your application, which is easily done via the `app:name` Artisan command. For example, if your application is named "SocialNet", you would run the following command: 59 | 60 | php artisan app:name SocialNet 61 | -------------------------------------------------------------------------------- /templates.md: -------------------------------------------------------------------------------- 1 | # Templates 2 | 3 | - [Blade Templating](#blade-templating) 4 | - [Other Blade Control Structures](#other-blade-control-structures) 5 | 6 | 7 | ## Blade Templating 8 | 9 | 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. 10 | 11 | #### Defining A Blade Layout 12 | 13 | 14 | 15 | 16 | 17 | App Name - @yield('title') 18 | 19 | 20 | @section('sidebar') 21 | This is the master sidebar. 22 | @show 23 | 24 |
25 | @yield('content') 26 |
27 | 28 | 29 | 30 | #### Using A Blade Layout 31 | 32 | @extends('layouts.master') 33 | 34 | @section('title', 'Page Title') 35 | 36 | @section('sidebar') 37 | @@parent 38 | 39 |

This is appended to the master sidebar.

40 | @stop 41 | 42 | @section('content') 43 |

This is my body content.

44 | @stop 45 | 46 | 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. 47 | 48 | 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: 49 | 50 | @yield('section', 'Default Content') 51 | 52 | 53 | ## Other Blade Control Structures 54 | 55 | #### Echoing Data 56 | 57 | Hello, {{ $name }}. 58 | 59 | The current UNIX timestamp is {{ time() }}. 60 | 61 | #### Echoing Data After Checking For Existence 62 | 63 | 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: 64 | 65 | {{ isset($name) ? $name : 'Default' }} 66 | 67 | However, instead of writing a ternary statement, Blade allows you to use the following convenient short-cut: 68 | 69 | {{ $name or 'Default' }} 70 | 71 | #### Displaying Raw Text With Curly Braces 72 | 73 | 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: 74 | 75 | @{{ This will not be processed by Blade }} 76 | 77 | If you don't want the data to be escaped, you may use the following syntax: 78 | 79 | Hello, {!! $name !!}. 80 | 81 | > **Note:** Be very careful when echoing content that is supplied by users of your application. Always use the double curly brace syntax to escape any HTML entities in the content. 82 | 83 | #### If Statements 84 | 85 | @if (count($records) === 1) 86 | I have one record! 87 | @elseif (count($records) > 1) 88 | I have multiple records! 89 | @else 90 | I don't have any records! 91 | @endif 92 | 93 | @unless (Auth::check()) 94 | You are not signed in. 95 | @endunless 96 | 97 | #### Loops 98 | 99 | @for ($i = 0; $i < 10; $i++) 100 | The current value is {{ $i }} 101 | @endfor 102 | 103 | @foreach ($users as $user) 104 |

This is user {{ $user->id }}

105 | @endforeach 106 | 107 | @forelse($users as $user) 108 |
  • {{ $user->name }}
  • 109 | @empty 110 |

    No users

    111 | @endforelse 112 | 113 | @while (true) 114 |

    I'm looping forever.

    115 | @endwhile 116 | 117 | #### Including Sub-Views 118 | 119 | @include('view.name') 120 | 121 | You may also pass an array of data to the included view: 122 | 123 | @include('view.name', ['some' => 'data']) 124 | 125 | #### Overwriting Sections 126 | 127 | To overwrite a section entirely, you may use the `overwrite` statement: 128 | 129 | @extends('list.item.container') 130 | 131 | @section('list.item.content') 132 |

    This is an item of type {{ $item->type }}

    133 | @overwrite 134 | 135 | #### Displaying Language Lines 136 | 137 | @lang('language.line') 138 | 139 | @choice('language.line', 1) 140 | 141 | #### Comments 142 | 143 | {{-- This comment will not be in the rendered HTML --}} 144 | 145 | -------------------------------------------------------------------------------- /testing.md: -------------------------------------------------------------------------------- 1 | # Testing 2 | 3 | - [Introduction](#introduction) 4 | - [Defining & Running Tests](#defining-and-running-tests) 5 | - [Test Environment](#test-environment) 6 | - [Calling Routes From Tests](#calling-routes-from-tests) 7 | - [Mocking Facades](#mocking-facades) 8 | - [Framework Assertions](#framework-assertions) 9 | - [Helper Methods](#helper-methods) 10 | - [Refreshing The Application](#refreshing-the-application) 11 | 12 | 13 | ## Introduction 14 | 15 | Laravel is built with unit 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. 16 | 17 | An example test file is provided in the `tests` directory. After installing a new Laravel application, simply run `phpunit` on the command line to run your tests. 18 | 19 | 20 | ## Defining & Running Tests 21 | 22 | To create a test case, simply create a new test file in the `tests` directory. The test class should extend `TestCase`. You may then define test methods as you normally would when using PHPUnit. 23 | 24 | #### An Example Test Class 25 | 26 | class FooTest extends TestCase { 27 | 28 | public function testSomethingIsTrue() 29 | { 30 | $this->assertTrue(true); 31 | } 32 | 33 | } 34 | 35 | You may run all of the tests for your application by executing the `phpunit` command from your terminal. 36 | 37 | > **Note:** If you define your own `setUp` method, be sure to call `parent::setUp`. 38 | 39 | 40 | ## Test Environment 41 | 42 | When running unit tests, Laravel will automatically set the configuration environment to `testing`. Also, Laravel includes configuration files for `session` and `cache` in the test environment. Both of these drivers are set to `array` while in the test environment, meaning no session or cache data will be persisted while testing. You are free to create other testing environment configurations as necessary. 43 | 44 | The `testing` environment variables may be configured in the `phpunit.xml` file. 45 | 46 | 47 | ## Calling Routes From Tests 48 | 49 | #### Calling A Route From A Test 50 | 51 | You may easily call one of your routes for a test using the `call` method: 52 | 53 | $response = $this->call('GET', 'user/profile'); 54 | 55 | $response = $this->call($method, $uri, $parameters, $cookies, $files, $server, $content); 56 | 57 | You may then inspect the `Illuminate\Http\Response` object: 58 | 59 | $this->assertEquals('Hello World', $response->getContent()); 60 | 61 | #### Calling A Controller From A Test 62 | 63 | You may also call a controller from a test: 64 | 65 | $response = $this->action('GET', 'HomeController@index'); 66 | 67 | $response = $this->action('GET', 'UserController@profile', ['user' => 1]); 68 | 69 | > **Note:** You do not need to specify the full controller namespace when using the `action` method. Only specify the portion of the class name that follows the `App\Http\Controllers` namespace. 70 | 71 | The `getContent` method will return the evaluated string contents of the response. If your route returns a `View`, you may access it using the `original` property: 72 | 73 | $view = $response->original; 74 | 75 | $this->assertEquals('John', $view['name']); 76 | 77 | To call a HTTPS route, you may use the `callSecure` method: 78 | 79 | $response = $this->callSecure('GET', 'foo/bar'); 80 | 81 | 82 | ## Mocking Facades 83 | 84 | When testing, you may often want to mock a call to a Laravel static facade. For example, consider the following controller action: 85 | 86 | public function getIndex() 87 | { 88 | Event::fire('foo', ['name' => 'Dayle']); 89 | 90 | return 'All done!'; 91 | } 92 | 93 | We can mock the call to the `Event` class by using the `shouldReceive` method on the facade, which will return an instance of a [Mockery](https://github.com/padraic/mockery) mock. 94 | 95 | #### Mocking A Facade 96 | 97 | public function testGetIndex() 98 | { 99 | Event::shouldReceive('fire')->once()->with('foo', ['name' => 'Dayle']); 100 | 101 | $this->call('GET', '/'); 102 | } 103 | 104 | > **Note:** You should not mock the `Request` facade. Instead, pass the input you desire into the `call` method when running your test. 105 | 106 | 107 | ## Framework Assertions 108 | 109 | Laravel ships with several `assert` methods to make testing a little easier: 110 | 111 | #### Asserting Responses Are OK 112 | 113 | public function testMethod() 114 | { 115 | $this->call('GET', '/'); 116 | 117 | $this->assertResponseOk(); 118 | } 119 | 120 | #### Asserting Response Statuses 121 | 122 | $this->assertResponseStatus(403); 123 | 124 | #### Asserting Responses Are Redirects 125 | 126 | $this->assertRedirectedTo('foo'); 127 | 128 | $this->assertRedirectedToRoute('route.name'); 129 | 130 | $this->assertRedirectedToAction('Controller@method'); 131 | 132 | #### Asserting A View Has Some Data 133 | 134 | public function testMethod() 135 | { 136 | $this->call('GET', '/'); 137 | 138 | $this->assertViewHas('name'); 139 | $this->assertViewHas('age', $value); 140 | } 141 | 142 | #### Asserting The Session Has Some Data 143 | 144 | public function testMethod() 145 | { 146 | $this->call('GET', '/'); 147 | 148 | $this->assertSessionHas('name'); 149 | $this->assertSessionHas('age', $value); 150 | } 151 | 152 | #### Asserting The Session Has Errors 153 | 154 | public function testMethod() 155 | { 156 | $this->call('GET', '/'); 157 | 158 | $this->assertSessionHasErrors(); 159 | 160 | // Asserting the session has errors for a given key... 161 | $this->assertSessionHasErrors('name'); 162 | 163 | // Asserting the session has errors for several keys... 164 | $this->assertSessionHasErrors(['name', 'age']); 165 | } 166 | 167 | #### Asserting Old Input Has Some Data 168 | 169 | public function testMethod() 170 | { 171 | $this->call('GET', '/'); 172 | 173 | $this->assertHasOldInput(); 174 | } 175 | 176 | 177 | ## Helper Methods 178 | 179 | The `TestCase` class contains several helper methods to make testing your application easier. 180 | 181 | #### Setting And Flushing Sessions From Tests 182 | 183 | $this->session(['foo' => 'bar']); 184 | 185 | $this->flushSession(); 186 | 187 | #### Setting The Currently Authenticated User 188 | 189 | You may set the currently authenticated user using the `be` method: 190 | 191 | $user = new User(['name' => 'John']); 192 | 193 | $this->be($user); 194 | 195 | You may re-seed your database from a test using the `seed` method: 196 | 197 | #### Re-Seeding Database From Tests 198 | 199 | $this->seed(); 200 | 201 | $this->seed('DatabaseSeeder'); 202 | 203 | More information on creating seeds may be found in the [migrations and seeding](/docs/migrations#database-seeding) section of the documentation. 204 | 205 | 206 | ## Refreshing The Application 207 | 208 | As you may already know, you can access your Application ([service container](/docs/{{version}}/container)) via `$this->app` from any test method. This service container instance is refreshed for each test class. If you wish to manually force the Application to be refreshed for a given method, you may use the `refreshApplication` method from your test method. This will reset any extra bindings, such as mocks, that have been placed in the IoC container since the test case started running. 209 | -------------------------------------------------------------------------------- /views.md: -------------------------------------------------------------------------------- 1 | # Views 2 | 3 | - [Basic Usage](#basic-usage) 4 | - [View Composers](#view-composers) 5 | 6 | 7 | ## Basic Usage 8 | 9 | Views contain the HTML served by your application, and serve as a convenient method of separating your controller and domain logic from your presentation logic. Views are stored in the `resources/views` directory. 10 | 11 | A simple view looks like this: 12 | 13 | 14 | 15 | 16 | 17 |

    Hello,

    18 | 19 | 20 | 21 | The view may be returned to the browser like so: 22 | 23 | Route::get('/', function() 24 | { 25 | return view('greeting', ['name' => 'James']); 26 | }); 27 | 28 | As you can see, the first argument passed to the `view` helper corresponds to the name of the view file in the `resources/views` directory. The second argument passed to helper is an array of data that should be made available to the view. 29 | 30 | Of course, views may also be nested within sub-directories of the `resources/views` directory. For example, if your view is stored at `resources/views/admin/profile.php`, it should be returned like so: 31 | 32 | return view('admin.profile', $data); 33 | 34 | #### Passing Data To Views 35 | 36 | // Using conventional approach 37 | $view = view('greeting')->with('name', 'Victoria'); 38 | 39 | // Using Magic Methods 40 | $view = view('greeting')->withName('Victoria'); 41 | 42 | In the example above, the variable `$name` is made accessible to the view and contains `Victoria`. 43 | 44 | If you wish, you may pass an array of data as the second parameter to the `view` helper: 45 | 46 | $view = view('greetings', $data); 47 | 48 | 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 it's corresponding key, like `{{ $key }}` (assuming `$data['$key']` exists). 49 | 50 | #### Sharing Data With All Views 51 | 52 | Occasionally, you may need to share a piece of data with all views that are rendered by your application. You have several options: the `view` helper, the `Illuminate\Contracts\View\Factory` [contract](/docs/{{version}}/contracts), or a wildcard [view composer](#view-composers). 53 | 54 | For example, using the `view` helper: 55 | 56 | view()->share('data', [1, 2, 3]); 57 | 58 | You may also use the `View` facade: 59 | 60 | View::share('data', [1, 2, 3]); 61 | 62 | Typically, you would place calls to the `share` method within a service provider's `boot` method. You are free to add them to the `AppServiceProvider` or generate a separate service provider to house them. 63 | 64 | > **Note:** When the `view` helper is called without arguments, it returns an implementation of the `Illuminate\Contracts\View\Factory` contract. 65 | 66 | #### Determining If A View Exists 67 | 68 | If you need to determine if a view exists, you may use the `exists` method: 69 | 70 | if (view()->exists('emails.customer')) 71 | { 72 | // 73 | } 74 | 75 | #### Returning A View From A File Path 76 | 77 | If you wish, you may generate a view from a fully-qualified file path: 78 | 79 | return view()->file($pathToFile, $data); 80 | 81 | 82 | ## View Composers 83 | 84 | 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 organizes that logic into a single location. 85 | 86 | #### Defining A View Composer 87 | 88 | Let's organize our 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: 89 | 90 | **Note:** 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. 127 | 128 | Remember, you will need to add the service provider to the `providers` array in the `config/app.php` configuration file. 129 | 130 | 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: 131 | 132 | users = $users; 156 | } 157 | 158 | /** 159 | * Bind data to the view. 160 | * 161 | * @param View $view 162 | * @return void 163 | */ 164 | public function compose(View $view) 165 | { 166 | $view->with('count', $this->users->count()); 167 | } 168 | 169 | } 170 | 171 | Just before the view is rendered, the composer's `compose` method is called with the `Illuminate\Contracts\View\View` instance. You may use the `with` method to bind data to the view. 172 | 173 | > **Note:** 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. 174 | 175 | #### Wildcard View Composers 176 | 177 | The `composer` method accepts the `*` character as a wildcard, so you may attach a composer to all views like so: 178 | 179 | View::composer('*', function($view) 180 | { 181 | // 182 | }); 183 | 184 | #### Attaching A Composer To Multiple Views 185 | 186 | You may also attach a view composer to multiple views at once: 187 | 188 | View::composer(['profile', 'dashboard'], 'App\Http\ViewComposers\MyViewComposer'); 189 | 190 | #### Defining Multiple Composers 191 | 192 | You may use the `composers` method to register a group of composers at the same time: 193 | 194 | View::composers([ 195 | 'App\Http\ViewComposers\AdminComposer' => ['admin.index', 'admin.profile'], 196 | 'App\Http\ViewComposers\UserComposer' => 'user', 197 | 'App\Http\ViewComposers\ProductComposer' => 'product' 198 | ]); 199 | 200 | ### View Creators 201 | 202 | View **creators** work almost exactly like view composers; however, they are fired immediately when the view is instantiated. To register a view creator, use the `creator` method: 203 | 204 | View::creator('profile', 'App\Http\ViewCreators\ProfileCreator'); 205 | --------------------------------------------------------------------------------