├── 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 |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 |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 |