Release Notes

Versioning Scheme

Laravel's versioning scheme maintains the following convention: paradigm.minor.patch. Minor framework releases are released every six months (January and July), while patch releases may be released as often as every week. Patch releases should never contain breaking changes.

When referencing the Laravel framework or its components from your application or package, you should always use a version constraint such as 5.4.*, since minor releases of Laravel do include breaking changes. However, we strive to always ensure you may update to a new minor release in one day or less.

Paradigm shifting releases are separated by many years and represent fundamental shifts in the framework's architecture and conventions. Currently, there is no paradigm shifting release under development.

Why Doesn't Laravel Use Semantic Versioning?

On one hand, all optional components of Laravel (Cashier, Dusk, Valet, Socialite, etc.) do use semantic versioning. However, the Laravel framework itself does not. The reason for this is because semantic versioning is a "reductionist" way of determining if two pieces of code are compatible. Even when using semantic versioning, you still must install the upgraded package and run your automated test suite to know if anything is actually incompatible with your code base.

So, instead, the Laravel framework uses a versioning scheme that is more communicative of the actual scope of the release. Furthermore, since patch releases never contain intentional breaking changes, you should never receive a breaking change as long as your version constraints follow the paradigm.minor.* convention.

Support Policy

For LTS releases, such as Laravel 5.1, bug fixes are provided for 2 years and security fixes are provided for 3 years. These releases provide the longest window of support and maintenance. For general releases, bug fixes are provided for 6 months and security fixes are provided for 1 year.

Laravel 5.4.22

Laravel 5.4.22 patches a security vulnerability in the Laravel 5.4 release series that allows phishing attempts on users of the application. Using the password reset system, malicious users can attempt to trick your users into entering their login credentials into a separate application that they control. Since the password reset notification uses the host of the incoming request to build the password reset URL, the host of the password reset URL may be spoofed. If users do not notice that they are not on their intended application's domain, they may accidentally enter their login credentials into a malicious application.

In Laravel 5.1 applications, the password reset notification is maintained by the developer, so this vulnerability may or may not be present. You should verify that your application generates an absolute URL for password reset links:

  1. {{ url('http://example.com/password/reset/'.$token) }}

Laravel 5.4

Laravel 5.4 continues the improvements made in Laravel 5.3 by adding support for Markdown based emails and notifications, the Laravel Dusk browser automation and testing framework, Laravel Mix, Blade "components" and "slots", route model binding on broadcast channels, higher order messages for Collections, object-based Eloquent events, job-level "retry" and "timeout" settings, "realtime" facades, improved support for Redis Cluster, custom pivot table models, middleware for request input trimming and cleaning, and more. In addition, the entire codebase of the framework was reviewed and refactored for general cleanliness.

{tip} This documentation summarizes the most notable improvements to the framework; however, more thorough change logs are always available on GitHub.

Markdown Mail & Notifications

{video} There is a free video tutorial for this feature available on Laracasts.

Markdown mailable messages allow you to take advantage of the pre-built templates and components of mail notifications in your mailables. Since the messages are written in Markdown, Laravel is able to render beautiful, responsive HTML templates for the messages while also automatically generating a plain-text counterpart. For example, a Markdown email might look something like the following:

  1. @component('mail::message')
  2. # Order Shipped
  3. Your order has been shipped!
  4. @component('mail::button', ['url' => $url])
  5. View Order
  6. @endcomponent
  7. Next Steps:
  8. - Track Your Order On Our Website
  9. - Pre-Sign For Delivery
  10. Thanks,<br>
  11. {{ config('app.name') }}
  12. @endcomponent

Using this simple Markdown template, Laravel is able to generate a responsive HTML email and plain-text counterpart:Release Notes - 图1To read more about Markdown mail and notifications, check out the full mail and notification documentation.

{tip} You may export all of the Markdown mail components to your own application for customization. To export the components, use the vendor:publish Artisan command to publish the laravel-mail asset tag.

Laravel Dusk

{video} There is a free video tutorial for this feature available on Laracasts.

Laravel Dusk provides an expressive, easy-to-use browser automation and testing API. By default, Dusk does not require you to install JDK or Selenium on your machine. Instead, Dusk uses a standalone ChromeDriver installation. However, you are free to utilize any other Selenium compatible driver you wish.

Since Dusk operates using a real browser, you are able to easily test and interact with your applications that heavily use JavaScript:

  1. /**
  2. * A basic browser test example.
  3. *
  4. * @return void
  5. */
  6. public function testBasicExample()
  7. {
  8. $user = factory(User::class)->create([
  9. 'email' => '[email protected]',
  10. ]);
  11. $this->browse(function ($browser) use ($user) {
  12. $browser->loginAs($user)
  13. ->visit('/home')
  14. ->press('Create Playlist')
  15. ->whenAvailable('.playlist-modal', function ($modal) {
  16. $modal->type('name', 'My Playlist')
  17. ->press('Create');
  18. });
  19. $browser->waitForText('Playlist Created');
  20. });
  21. }

For more information on Dusk, consult the full Dusk documentation.

Laravel Mix

{video} There is a free video tutorial for this feature available on Laracasts.

Laravel Mix is the spiritual successor of Laravel Elixir, and its entirely based on Webpack instead of Gulp. Laravel Mix provides a fluent API for defining Webpack build steps for your Laravel application using several common CSS and JavaScript pre-processors. Through simple method chaining, you can fluently define your asset pipeline. For example:

  1. mix.js('resources/assets/js/app.js', 'public/js')
  2. .sass('resources/assets/sass/app.scss', 'public/css');

Blade Components & Slots

{video} There is a free video tutorial for this feature available on Laracasts.

Blade components and slots provide similar benefits to sections and layouts; however, some may find the mental model of components and slots easier to understand. First, let's imagine a reusable "alert" component we would like to reuse throughout our application:

  1. <!-- /resources/views/alert.blade.php -->
  2. <div class="alert alert-danger">
  3. {{ $slot }}
  4. </div>

The {{ $slot }} variable will contain the content we wish to inject into the component. Now, to construct this component, we can use the @component Blade directive:

  1. @component('alert')
  2. <strong>Whoops!</strong> Something went wrong!
  3. @endcomponent

Named slots allow you to provide multiple slots into a single component:

  1. <!-- /resources/views/alert.blade.php -->
  2. <div class="alert alert-danger">
  3. <div class="alert-title">{{ $title }}</div>
  4. {{ $slot }}
  5. </div>

Named slots may be injected using the @slot directive. Any content is not within a @slot directive will be passed to the component in the $slot variable:

  1. @component('alert')
  2. @slot('title')
  3. Forbidden
  4. @endslot
  5. You are not allowed to access this resource!
  6. @endcomponent

To read more about components and slots, consult the full Blade documentation.

Broadcast Model Binding

Just like HTTP routes, channel routes may now take advantage of implicit and explicit route model binding. For example, instead of receiving the string or numeric order ID, you may request an actual Order model instance:

  1. use App\Order;
  2. Broadcast::channel('order.{order}', function ($user, Order $order) {
  3. return $user->id === $order->user_id;
  4. });

To read more about broadcast model binding, consult the full event broadcasting documentation.

Collection Higher Order Messages

{video} There is a free video tutorial for this feature available on Laracasts.

Collections now provide support for "higher order messages", which are short-cuts for performing common actions on collections. The collection methods that provide higher order messages are: contains, each, every, filter, first, map, partition, reject, sortBy, sortByDesc, and sum.

Each higher order message can be accessed as a dynamic property on a collection instance. For instance, let's use the each higher order message to call a method on each object within a collection:

  1. $users = User::where('votes', '>', 500)->get();
  2. $users->each->markAsVip();

Likewise, we can use the sum higher order message to gather the total number of "votes" for a collection of users:

  1. $users = User::where('group', 'Development')->get();
  2. return $users->sum->votes;

Object Based Eloquent Events

{video} There is a free video tutorial for this feature available on Laracasts.

Eloquent event handlers may now be mapped to event objects. This provides a more intuitive way of handling Eloquent events and makes it easier to test the events. To get started, define an $events property on your Eloquent model that maps various points of the Eloquent model's lifecycle to your own event classes:

  1. <?php
  2. namespace App;
  3. use App\Events\UserSaved;
  4. use App\Events\UserDeleted;
  5. use Illuminate\Notifications\Notifiable;
  6. use Illuminate\Foundation\Auth\User as Authenticatable;
  7. class User extends Authenticatable
  8. {
  9. use Notifiable;
  10. /**
  11. * The event map for the model.
  12. *
  13. * @var array
  14. */
  15. protected $events = [
  16. 'saved' => UserSaved::class,
  17. 'deleted' => UserDeleted::class,
  18. ];
  19. }

Job Level Retry & Timeout

Previously, queue job "retry" and "timeout" settings could only be configured globally for all jobs on the command line. However, in Laravel 5.4, these settings may be configured on a per-job basis by defining them directly on the job class:

  1. <?php
  2. namespace App\Jobs;
  3. class ProcessPodcast implements ShouldQueue
  4. {
  5. /**
  6. * The number of times the job may be attempted.
  7. *
  8. * @var int
  9. */
  10. public $tries = 5;
  11. /**
  12. * The number of seconds the job can run before timing out.
  13. *
  14. * @var int
  15. */
  16. public $timeout = 120;
  17. }

For more information about these settings, consult the full queue documentation.

Request Sanitization Middleware

{video} There is a free video tutorial for this feature available on Laracasts.

Laravel 5.4 includes two new middleware in the default middleware stack: TrimStrings and ConvertEmptyStringsToNull:

  1. /**
  2. * The application's global HTTP middleware stack.
  3. *
  4. * These middleware are run during every request to your application.
  5. *
  6. * @var array
  7. */
  8. protected $middleware = [
  9. \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
  10. \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
  11. \App\Http\Middleware\TrimStrings::class,
  12. \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
  13. ];

These middleware will automatically trim request input values and convert any empty strings to null. This helps you normalize the input for every request entering into your application and not have to worry about continually calling the trim function in every route and controller.

"Realtime" Facades

{video} There is a free video tutorial for this feature available on Laracasts.

Previously, only Laravel's own built-in services exposed facades, which provide quick, terse access to their methods via the service container. However, in Laravel 5.4, you may easily convert any of your application's classes into a facade in realtime simply by prefixing the imported class name with Facades. For example, imagine your application contains a class like the following:

  1. <?php
  2. namespace App\Services;
  3. class PaymentGateway
  4. {
  5. protected $tax;
  6. /**
  7. * Create a new payment gateway instance.
  8. *
  9. * @param TaxCalculator $tax
  10. * @return void
  11. */
  12. public function __construct(TaxCalculator $tax)
  13. {
  14. $this->tax = $tax;
  15. }
  16. /**
  17. * Pay the given amount.
  18. *
  19. * @param int $amount
  20. * @return void
  21. */
  22. public function pay($amount)
  23. {
  24. // Pay an amount...
  25. }
  26. }

You may easily use this class as a facade like so:

  1. use Facades\ {
  2. App\Services\PaymentGateway
  3. };
  4. Route::get('/pay/{amount}', function ($amount) {
  5. PaymentGateway::pay($amount);
  6. });

Of course, if you leverage a realtime facade in this way, you may easily write a test for the interaction using Laravel's facade mocking capabilities:

  1. PaymentGateway::shouldReceive('pay')->with('100');

Custom Pivot Table Models

In Laravel 5.3, all "pivot" table models for belongsToMany relationships used the same built-in Pivot model instance. In Laravel 5.4, you may define custom models for your pivot tables. If you would like to define a custom model to represent the intermediate table of your relationship, use the using method when defining the relationship:

  1. <?php
  2. namespace App;
  3. use Illuminate\Database\Eloquent\Model;
  4. class Role extends Model
  5. {
  6. /**
  7. * The users that belong to the role.
  8. */
  9. public function users()
  10. {
  11. return $this->belongsToMany('App\User')->using('App\UserRole');
  12. }
  13. }

Improved Redis Cluster Support

Previously, it was not possible to define Redis connections to single hosts and to clusters in the same application. In Laravel 5.4, you may now define Redis connections to multiple single hosts and multiple clusters within the same application. For more information on Redis in Laravel, please consult the full Redis documentation.

Migration Default String Length

Laravel 5.4 uses the utf8mb4 character set by default, which includes support for storing "emojis" in the database. If you are upgrading your application from Laravel 5.3, you are not required to switch to this character set.

If you choose to switch to this character set manually and are running a version of MySQL older than the 5.7.7 release, you may need to manually configure the default string length generated by migrations. You may configure this by calling the Schema::defaultStringLength method within your AppServiceProvider:

  1. use Illuminate\Support\Facades\Schema;
  2. /**
  3. * Bootstrap any application services.
  4. *
  5. * @return void
  6. */
  7. public function boot()
  8. {
  9. Schema::defaultStringLength(191);
  10. }

Laravel 5.3

Laravel 5.3 continues the improvements made in Laravel 5.2 by adding a driver based notification system, robust realtime support via Laravel Echo, painless OAuth2 servers via Laravel Passport, full-text model searching via Laravel Scout, Webpack support in Laravel Elixir, "mailable" objects, explicit separation of web and api routes, Closure based console commands, convenient helpers for storing uploaded files, support for POPO and single-action controllers, improved default frontend scaffolding, and more.

Notifications

{video} There is a free video tutorial for this feature available on Laracasts.

Laravel Notifications provide a simple, expressive API for sending notifications across a variety of delivery channels such as email, Slack, SMS, and more. For example, you may define a notification that an invoice has been paid and deliver that notification via email and SMS. Then, you may send the notification using a single, simple method:

  1. $user->notify(new InvoicePaid($invoice));

There is already a wide variety of community written drivers for notifications, including support for iOS and Android notifications. To learn more about notifications, be sure to check out the full notification documentation.

WebSockets / Event Broadcasting

While event broadcasting existed in previous versions of Laravel, the Laravel 5.3 release greatly improves this feature of the framework by adding channel-level authentication for private and presence WebSocket channels:

  1. /*
  2. * Authenticate the channel subscription...
  3. */
  4. Broadcast::channel('orders.*', function ($user, $orderId) {
  5. return $user->placedOrder($orderId);
  6. });

Laravel Echo, a new JavaScript package installable via NPM, has also been released to provide a simple, beautiful API for subscribing to channels and listening for your server-side events in your client-side JavaScript application. Echo includes support for Pusher and Socket.io:

  1. Echo.channel('orders.' + orderId)
  2. .listen('ShippingStatusUpdated', (e) => {
  3. console.log(e.description);
  4. });

In addition to subscribing to traditional channels, Laravel Echo also makes it a breeze to subscribe to presence channels which provide information about who is listening on a given channel:

  1. Echo.join('chat.' + roomId)
  2. .here((users) => {
  3. //
  4. })
  5. .joining((user) => {
  6. console.log(user.name);
  7. })
  8. .leaving((user) => {
  9. console.log(user.name);
  10. });

To learn more about Echo and event broadcasting, check out the full documentation.

Laravel Passport (OAuth2 Server)

{video} There is a free video tutorial for this feature available on Laracasts.

Laravel 5.3 makes API authentication a breeze using Laravel Passport, which provides a full OAuth2 server implementation for your Laravel application in a matter of minutes. Passport is built on top of the League OAuth2 server that is maintained by Alex Bilbie.

Passport makes it painless to issue access tokens via OAuth2 authorization codes. You may also allow your users to create "personal access tokens" via your web UI. To get you started quickly, Passport includes Vue components that can serve as a starting point for your OAuth2 dashboard, allowing users to create clients, revoke access tokens, and more:

  1. <passport-clients></passport-clients>
  2. <passport-authorized-clients></passport-authorized-clients>
  3. <passport-personal-access-tokens></passport-personal-access-tokens>

If you do not want to use the Vue components, you are welcome to provide your own frontend dashboard for managing clients and access tokens. Passport exposes a simple JSON API that you may use with any JavaScript framework you choose.

Of course, Passport also makes it simple to define access token scopes that may be requested by application's consuming your API:

  1. Passport::tokensCan([
  2. 'place-orders' => 'Place new orders',
  3. 'check-status' => 'Check order status',
  4. ]);

In addition, Passport includes helpful middleware for verifying that an access token authenticated request contains the necessary token scopes:

  1. Route::get('/orders/{order}/status', function (Order $order) {
  2. // Access token has "check-status" scope...
  3. })->middleware('scope:check-status');

Lastly, Passport includes support for consuming your own API from your JavaScript application without worrying about passing access tokens. Passport achieves this through encrypted JWT cookies and synchronized CSRF tokens, allowing you to focus on what matters: your application. For more information on Passport, be sure to check out its full documentation.

Search (Laravel Scout)

Laravel Scout provides a simple, driver based solution for adding full-text search to your Eloquent models. Using model observers, Scout will automatically keep your search indexes in sync with your Eloquent records. Currently, Scout ships with an Algolia driver; however, writing custom drivers is simple and you are free to extend Scout with your own search implementations.

Making models searchable is as simple as adding a Searchable trait to the model:

  1. <?php
  2. namespace App;
  3. use Laravel\Scout\Searchable;
  4. use Illuminate\Database\Eloquent\Model;
  5. class Post extends Model
  6. {
  7. use Searchable;
  8. }

Once the trait has been added to your model, its information will be kept in sync with your search indexes by simply saving the model:

  1. $order = new Order;
  2. // ...
  3. $order->save();

Once your models have been indexed, its a breeze to perform full-text searches across all of your models. You may even paginate your search results:

  1. return Order::search('Star Trek')->get();
  2. return Order::search('Star Trek')->where('user_id', 1)->paginate();

Of course, Scout has many more features which are covered in the full documentation.

Mailable Objects

{video} There is a free video tutorial for this feature available on Laracasts.

Laravel 5.3 ships with support for mailable objects. These objects allow you to represent your email messages as a simple objects instead of customizing mail messages within Closures. For example, you may define a simple mailable object for a "welcome" email:

  1. class WelcomeMessage extends Mailable
  2. {
  3. use Queueable, SerializesModels;
  4. /**
  5. * Build the message.
  6. *
  7. * @return $this
  8. */
  9. public function build()
  10. {
  11. return $this->view('emails.welcome');
  12. }
  13. }

Once the mailable object has been defined, you can send it to a user using a simple, expressive API. Mailable objects are great for discovering the intent of your messages while scanning your code:

  1. Mail::to($user)->send(new WelcomeMessage);

Of course, you may also mark mailable objects as "queueable" so that they will be sent in the background by your queue workers:

  1. class WelcomeMessage extends Mailable implements ShouldQueue
  2. {
  3. //
  4. }

For more information on mailable objects, be sure to check out the mail documentation.

Storing Uploaded Files

{video} There is a free video tutorial for this feature available on Laracasts.

In web applications, one of the most common use-cases for storing files is storing user uploaded files such as profile pictures, photos, and documents. Laravel 5.3 makes it very easy to store uploaded files using the new store method on an uploaded file instance. Simply call the store method with the path at which you wish to store the uploaded file:

  1. /**
  2. * Update the avatar for the user.
  3. *
  4. * @param Request $request
  5. * @return Response
  6. */
  7. public function update(Request $request)
  8. {
  9. $path = $request->file('avatar')->store('avatars', 's3');
  10. return $path;
  11. }

For more information on storing uploaded files, check out the full documentation.

Webpack & Laravel Elixir

Along with Laravel 5.3, Laravel Elixir 6.0 has been released with baked-in support for the Webpack and Rollup JavaScript module bundlers. By default, the Laravel 5.3 gulpfile.js file now uses Webpack to compile your JavaScript. The full Laravel Elixir documentation contains more information on both of these bundlers:

  1. elixir(mix => {
  2. mix.sass('app.scss')
  3. .webpack('app.js');
  4. });

Frontend Structure

{video} There is a free video tutorial for this feature available on Laracasts.

Laravel 5.3 ships with a more modern frontend structure. This primarily affects the make:auth authentication scaffolding. Instead of loading frontend assets from a CDN, dependencies are specified in the default package.json file.

In addition, support for single file Vue components is now included out of the box. A sample Example.vue component is included in the resources/assets/js/components directory. In addition, the new resources/assets/js/app.js file bootstraps and configures your JavaScript libraries and, if applicable, Vue components.

This structure provides more guidance on how to begin developing modern, robust JavaScript applications, without requiring your application to use any given JavaScript or CSS framework. For more information on getting started with modern Laravel frontend development, check out the new introductory frontend documentation.

Routes Files

By default, fresh Laravel 5.3 applications contain two HTTP route files in a new top-level routes directory. The web and api route files provide more explicit guidance in how to split the routes for your web interface and your API. The routes in the api route file are automatically assigned the api prefix by the RouteServiceProvider.

Closure Console Commands

In addition to being defined as command classes, Artisan commands may now be defined as simple Closures in the commands method of your app/Console/Kernel.php file. In fresh Laravel 5.3 applications, the commands method loads a routes/console.php file which allows you to define your Console commands as route-like, Closure based entry points into your application:

  1. Artisan::command('build {project}', function ($project) {
  2. $this->info('Building project...');
  3. });

For more information on Closure commands, check out the full Artisan documentation.

The $loop Variable

{video} There is a free video tutorial for this feature available on Laracasts.

When looping within a Blade template, a $loop variable will be available inside of your loop. This variable provides access to some useful bits of information such as the current loop index and whether this is the first or last iteration through the loop:

  1. @foreach ($users as $user)
  2. @if ($loop->first)
  3. This is the first iteration.
  4. @endif
  5. @if ($loop->last)
  6. This is the last iteration.
  7. @endif
  8. <p>This is user {{ $user->id }}</p>
  9. @endforeach

For more information, consult the full Blade documentation.

Laravel 5.2

Laravel 5.2 continues the improvements made in Laravel 5.1 by adding multiple authentication driver support, implicit model binding, simplified Eloquent global scopes, opt-in authentication scaffolding, middleware groups, rate limiting middleware, array validation improvements, and more.

Authentication Drivers / "Multi-Auth"

In previous versions of Laravel, only the default, session-based authentication driver was supported out of the box, and you could not have more than one authenticatable model instance per application.

However, in Laravel 5.2, you may define additional authentication drivers as well define multiple authenticatable models or user tables, and control their authentication process separately from each other. For example, if your application has one database table for "admin" users and one database table for "student" users, you may now use the Auth methods to authenticate against each of these tables separately.

Authentication Scaffolding

Laravel already makes it easy to handle authentication on the back-end; however, Laravel 5.2 provides a convenient, lightning-fast way to scaffold the authentication views for your front-end. Simply execute the make:auth command on your terminal:

  1. php artisan make:auth

This command will generate plain, Bootstrap compatible views for user login, registration, and password reset. The command will also update your routes file with the appropriate routes.

{note} This feature is only meant to be used on new applications, not during application upgrades.

Implicit Model Binding

Implicit model binding makes it painless to inject relevant models directly into your routes and controllers. For example, assume you have a route defined like the following:

  1. use App\User;
  2. Route::get('/user/{user}', function (User $user) {
  3. return $user;
  4. });

In Laravel 5.1, you would typically need to use the Route::model method to instruct Laravel to inject the App\User instance that matches the {user} parameter in your route definition. However, in Laravel 5.2, the framework will automatically inject this model based on the URI segment, allowing you to quickly gain access to the model instances you need.

Laravel will automatically inject the model when the route parameter segment ({user}) matches the route Closure or controller method's corresponding variable name ($user) and the variable is type-hinting an Eloquent model class.

Middleware Groups

Middleware groups allow you to group several route middleware under a single, convenient key, allowing you to assign several middleware to a route at once. For example, this can be useful when building a web UI and an API within the same application. You may group the session and CSRF routes into a web group, and perhaps the rate limiter in the api group.

In fact, the default Laravel 5.2 application structure takes exactly this approach. For example, in the default App\Http\Kernel.php file you will find the following:

  1. /**
  2. * The application's route middleware groups.
  3. *
  4. * @var array
  5. */
  6. protected $middlewareGroups = [
  7. 'web' => [
  8. \App\Http\Middleware\EncryptCookies::class,
  9. \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
  10. \Illuminate\Session\Middleware\StartSession::class,
  11. \Illuminate\View\Middleware\ShareErrorsFromSession::class,
  12. \App\Http\Middleware\VerifyCsrfToken::class,
  13. ],
  14. 'api' => [
  15. 'throttle:60,1',
  16. ],
  17. ];

Then, the web group may be assigned to routes like so:

  1. Route::group(['middleware' => ['web']], function () {
  2. //
  3. });

However, keep in mind the web middleware group is already applied to your routes by default since the RouteServiceProvider includes it in the default middleware group.

Rate Limiting

A new rate limiter middleware is now included with the framework, allowing you to easily limit the number of requests that a given IP address can make to a route over a specified number of minutes. For example, to limit a route to 60 requests every minute from a single IP address, you may do the following:

  1. Route::get('/api/users', ['middleware' => 'throttle:60,1', function () {
  2. //
  3. }]);

Array Validation

Validating array form input fields is much easier in Laravel 5.2. For example, to validate that each e-mail in a given array input field is unique, you may do the following:

  1. $validator = Validator::make($request->all(), [
  2. 'person.*.email' => 'email|unique:users'
  3. ]);

Likewise, you may use the * character when specifying your validation messages in your language files, making it a breeze to use a single validation message for array based fields:

  1. 'custom' => [
  2. 'person.*.email' => [
  3. 'unique' => 'Each person must have a unique e-mail address',
  4. ]
  5. ],

Bail Validation Rule

A new bail validation rule has been added, which instructs the validator to stop validating after the first validation failure for a given rule. For example, you may now prevent the validator from running a unique check if an attribute fails an integer check:

  1. $this->validate($request, [
  2. 'user_id' => 'bail|integer|unique:users'
  3. ]);

Eloquent Global Scope Improvements

In previous versions of Laravel, global Eloquent scopes were complicated and error-prone to implement; however, in Laravel 5.2, global query scopes only require you to implement a single, simple method: apply.

For more information on writing global scopes, check out the full Eloquent documentation.

Laravel 5.1.11

Laravel 5.1.11 introduces authorization support out of the box! Conveniently organize your application's authorization logic using simple callbacks or policy classes, and authorize actions using simple, expressive methods.

For more information, please refer to the authorization documentation.

Laravel 5.1.4

Laravel 5.1.4 introduces simple login throttling to the framework. Consult the authentication documentation for more information.

Laravel 5.1

Laravel 5.1 continues the improvements made in Laravel 5.0 by adopting PSR-2 and adding event broadcasting, middleware parameters, Artisan improvements, and more.

PHP 5.5.9+

Since PHP 5.4 will enter "end of life" in September and will no longer receive security updates from the PHP development team, Laravel 5.1 requires PHP 5.5.9 or greater. PHP 5.5.9 allows compatibility with the latest versions of popular PHP libraries such as Guzzle and the AWS SDK.

LTS

Laravel 5.1 is the first release of Laravel to receive long term support. Laravel 5.1 will receive bug fixes for 2 years and security fixes for 3 years. This support window is the largest ever provided for Laravel and provides stability and peace of mind for larger, enterprise clients and customers.

PSR-2

The PSR-2 coding style guide has been adopted as the default style guide for the Laravel framework. Additionally, all generators have been updated to generate PSR-2 compatible syntax.

Documentation

Every page of the Laravel documentation has been meticulously reviewed and dramatically improved. All code examples have also been reviewed and expanded to provide more relevance and context.

Event Broadcasting

In many modern web applications, web sockets are used to implement realtime, live-updating user interfaces. When some data is updated on the server, a message is typically sent over a websocket connection to be handled by the client.

To assist you in building these types of applications, Laravel makes it easy to "broadcast" your events over a websocket connection. Broadcasting your Laravel events allows you to share the same event names between your server-side code and your client-side JavaScript framework.

To learn more about event broadcasting, check out the event documentation.

Middleware Parameters

Middleware can now receive additional custom parameters. For example, if your application needs to verify that the authenticated user has a given "role" before performing a given action, you could create a RoleMiddleware that receives a role name as an additional argument:

  1. <?php
  2. namespace App\Http\Middleware;
  3. use Closure;
  4. class RoleMiddleware
  5. {
  6. /**
  7. * Run the request filter.
  8. *
  9. * @param \Illuminate\Http\Request $request
  10. * @param \Closure $next
  11. * @param string $role
  12. * @return mixed
  13. */
  14. public function handle($request, Closure $next, $role)
  15. {
  16. if (! $request->user()->hasRole($role)) {
  17. // Redirect...
  18. }
  19. return $next($request);
  20. }
  21. }

Middleware parameters may be specified when defining the route by separating the middleware name and parameters with a :. Multiple parameters should be delimited by commas:

  1. Route::put('post/{id}', ['middleware' => 'role:editor', function ($id) {
  2. //
  3. }]);

For more information on middleware, check out the middleware documentation.

Testing Overhaul

The built-in testing capabilities of Laravel have been dramatically improved. A variety of new methods provide a fluent, expressive interface for interacting with your application and examining its responses. For example, check out the following test:

  1. public function testNewUserRegistration()
  2. {
  3. $this->visit('/register')
  4. ->type('Taylor', 'name')
  5. ->check('terms')
  6. ->press('Register')
  7. ->seePageIs('/dashboard');
  8. }

For more information on testing, check out the testing documentation.

Model Factories

Laravel now ships with an easy way to create stub Eloquent models using model factories. Model factories allow you to easily define a set of "default" attributes for your Eloquent model, and then generate test model instances for your tests or database seeds. Model factories also take advantage of the powerful Faker PHP library for generating random attribute data:

  1. $factory->define(App\User::class, function ($faker) {
  2. return [
  3. 'name' => $faker->name,
  4. 'email' => $faker->email,
  5. 'password' => str_random(10),
  6. 'remember_token' => str_random(10),
  7. ];
  8. });

For more information on model factories, check out the documentation.

Artisan Improvements

Artisan commands may now be defined using a simple, route-like "signature", which provides an extremely simple interface for defining command line arguments and options. For example, you may define a simple command and its options like so:

  1. /**
  2. * The name and signature of the console command.
  3. *
  4. * @var string
  5. */
  6. protected $signature = 'email:send {user} {--force}';

For more information on defining Artisan commands, consult the Artisan documentation.

Folder Structure

To better express intent, the app/Commands directory has been renamed to app/Jobs. Additionally, the app/Handlers directory has been consolidated into a single app/Listeners directory which simply contains event listeners. However, this is not a breaking change and you are not required to update to the new folder structure to use Laravel 5.1.

Encryption

In previous versions of Laravel, encryption was handled by the mcrypt PHP extension. However, beginning in Laravel 5.1, encryption is handled by the openssl extension, which is more actively maintained.

Laravel 5.0

Laravel 5.0 introduces a fresh application structure to the default Laravel project. This new structure serves as a better foundation for building a robust application in Laravel, as well as embraces new auto-loading standards (PSR-4) throughout the application. First, let's examine some of the major changes:

New Folder Structure

The old app/models directory has been entirely removed. Instead, all of your code lives directly within the app folder, and, by default, is organized to the App namespace. This default namespace can be quickly changed using the new app:name Artisan command.

Controllers, middleware, and requests (a new type of class in Laravel 5.0) are now grouped under the app/Http directory, as they are all classes related to the HTTP transport layer of your application. Instead of a single, flat file of route filters, all middleware are now broken into their own class files.

A new app/Providers directory replaces the app/start files from previous versions of Laravel 4.x. These service providers provide various bootstrapping functions to your application, such as error handling, logging, route loading, and more. Of course, you are free to create additional service providers for your application.

Application language files and views have been moved to the resources directory.

Contracts

All major Laravel components implement interfaces which are located in the illuminate/contracts repository. This repository has no external dependencies. Having a convenient, centrally located set of interfaces you may use for decoupling and dependency injection will serve as an easy alternative option to Laravel Facades.

For more information on contracts, consult the full documentation.

Route Cache

If your application is made up entirely of controller routes, you may utilize the new route:cache Artisan command to drastically speed up the registration of your routes. This is primarily useful on applications with 100+ routes and will drastically speed up this portion of your application.

Route Middleware

In addition to Laravel 4 style route "filters", Laravel 5 now supports HTTP middleware, and the included authentication and CSRF "filters" have been converted to middleware. Middleware provides a single, consistent interface to replace all types of filters, allowing you to easily inspect, and even reject, requests before they enter your application.

For more information on middleware, check out the documentation.

Controller Method Injection

In addition to the existing constructor injection, you may now type-hint dependencies on controller methods. The service container will automatically inject the dependencies, even if the route contains other parameters:

  1. public function createPost(Request $request, PostRepository $posts)
  2. {
  3. //
  4. }

Authentication Scaffolding

User registration, authentication, and password reset controllers are now included out of the box, as well as simple corresponding views, which are located at resources/views/auth. In addition, a "users" table migration has been included with the framework. Including these simple resources allows rapid development of application ideas without bogging down on authentication boilerplate. The authentication views may be accessed on the auth/login and auth/register routes. The App\Services\Auth\Registrar service is responsible for user validation and creation.

Event Objects

You may now define events as objects instead of simply using strings. For example, check out the following event:

  1. <?php
  2. class PodcastWasPurchased
  3. {
  4. public $podcast;
  5. public function __construct(Podcast $podcast)
  6. {
  7. $this->podcast = $podcast;
  8. }
  9. }

The event may be dispatched like normal:

  1. Event::fire(new PodcastWasPurchased($podcast));

Of course, your event handler will receive the event object instead of a list of data:

  1. <?php
  2. class ReportPodcastPurchase
  3. {
  4. public function handle(PodcastWasPurchased $event)
  5. {
  6. //
  7. }
  8. }

For more information on working with events, check out the full documentation.

Commands / Queueing

In addition to the queue job format supported in Laravel 4, Laravel 5 allows you to represent your queued jobs as simple command objects. These commands live in the app/Commands directory. Here's a sample command:

  1. <?php
  2. class PurchasePodcast extends Command implements SelfHandling, ShouldBeQueued
  3. {
  4. use SerializesModels;
  5. protected $user, $podcast;
  6. /**
  7. * Create a new command instance.
  8. *
  9. * @return void
  10. */
  11. public function __construct(User $user, Podcast $podcast)
  12. {
  13. $this->user = $user;
  14. $this->podcast = $podcast;
  15. }
  16. /**
  17. * Execute the command.
  18. *
  19. * @return void
  20. */
  21. public function handle()
  22. {
  23. // Handle the logic to purchase the podcast...
  24. event(new PodcastWasPurchased($this->user, $this->podcast));
  25. }
  26. }

The base Laravel controller utilizes the new DispatchesCommands trait, allowing you to easily dispatch your commands for execution:

$this->dispatch(new PurchasePodcastCommand($user, $podcast));

Of course, you may also use commands for tasks that are executed synchronously (are not queued). In fact, using commands is a great way to encapsulate complex tasks your application needs to perform. For more information, check out the command bus documentation.

Database Queue

A database queue driver is now included in Laravel, providing a simple, local queue driver that requires no extra package installation beyond your database software.

Laravel Scheduler

In the past, developers have generated a Cron entry for each console command they wished to schedule. However, this is a headache. Your console schedule is no longer in source control, and you must SSH into your server to add the Cron entries. Let's make our lives easier. The Laravel command scheduler allows you to fluently and expressively define your command schedule within Laravel itself, and only a single Cron entry is needed on your server.

It looks like this:

$schedule->command('artisan:command')->dailyAt('15:00');

Of course, check out the full documentation to learn all about the scheduler!

Tinker / Psysh

The php artisan tinker command now utilizes Psysh by Justin Hileman, a more robust REPL for PHP. If you liked Boris in Laravel 4, you're going to love Psysh. Even better, it works on Windows! To get started, just try:

php artisan tinker

DotEnv

Instead of a variety of confusing, nested environment configuration directories, Laravel 5 now utilizes DotEnv by Vance Lucas. This library provides a super simple way to manage your environment configuration, and makes environment detection in Laravel 5 a breeze. For more details, check out the full configuration documentation.

Laravel Elixir

Laravel Elixir, by Jeffrey Way, provides a fluent, expressive interface to compiling and concatenating your assets. If you've ever been intimidated by learning Grunt or Gulp, fear no more. Elixir makes it a cinch to get started using Gulp to compile your Less, Sass, and CoffeeScript. It can even run your tests for you!

For more information on Elixir, check out the full documentation.

Laravel Socialite

Laravel Socialite is an optional, Laravel 5.0+ compatible package that provides totally painless authentication with OAuth providers. Currently, Socialite supports Facebook, Twitter, Google, and GitHub. Here's what it looks like:

public function redirectForAuth()
{
    return Socialize::with('twitter')->redirect();
}

public function getUserFromProvider()
{
    $user = Socialize::with('twitter')->user();
}

No more spending hours writing OAuth authentication flows. Get started in minutes! The full documentation has all the details.

Flysystem Integration

Laravel now includes the powerful Flysystem filesystem abstraction library, providing pain free integration with local, Amazon S3, and Rackspace cloud storage - all with one, unified and elegant API! Storing a file in Amazon S3 is now as simple as:

Storage::put('file.txt', 'contents');

For more information on the Laravel Flysystem integration, consult the full documentation.

Form Requests

Laravel 5.0 introduces form requests, which extend the Illuminate\Foundation\Http\FormRequest class. These request objects can be combined with controller method injection to provide a boiler-plate free method of validating user input. Let's dig in and look at a sample FormRequest:

<?php

namespace App\Http\Requests;

class RegisterRequest extends FormRequest
{
    public function rules()
    {
        return [
            'email' => 'required|email|unique:users',
            'password' => 'required|confirmed|min:8',
        ];
    }

    public function authorize()
    {
        return true;
    }
}

Once the class has been defined, we can type-hint it on our controller action:

public function register(RegisterRequest $request)
{
    var_dump($request->input());
}

When the Laravel service container identifies that the class it is injecting is a FormRequest instance, the request will automatically be validated. This means that if your controller action is called, you can safely assume the HTTP request input has been validated according to the rules you specified in your form request class. Even more, if the request is invalid, an HTTP redirect, which you may customize, will automatically be issued, and the error messages will be either flashed to the session or converted to JSON. Form validation has never been more simple. For more information on FormRequest validation, check out the documentation.

Simple Controller Request Validation

The Laravel 5 base controller now includes a ValidatesRequests trait. This trait provides a simple validate method to validate incoming requests. If FormRequests are a little too much for your application, check this out:

public function createPost(Request $request)
{
    $this->validate($request, [
        'title' => 'required|max:255',
        'body' => 'required',
    ]);
}

If the validation fails, an exception will be thrown and the proper HTTP response will automatically be sent back to the browser. The validation errors will even be flashed to the session! If the request was an AJAX request, Laravel even takes care of sending a JSON representation of the validation errors back to you.

For more information on this new method, check out the documentation.

New Generators

To complement the new default application structure, new Artisan generator commands have been added to the framework. See php artisan list for more details.

Configuration Cache

You may now cache all of your configuration in a single file using the config:cache command.

Symfony VarDumper

The popular dd helper function, which dumps variable debug information, has been upgraded to use the amazing Symfony VarDumper. This provides color-coded output and even collapsing of arrays. Just try the following in your project:

dd([1, 2, 3]);

Laravel 4.2

The full change list for this release by running the php artisan changes command from a 4.2 installation, or by viewing the change file on GitHub. These notes only cover the major enhancements and changes for the release.

{note} During the 4.2 release cycle, many small bug fixes and enhancements were incorporated into the various Laravel 4.1 point releases. So, be sure to check the change list for Laravel 4.1 as well!

PHP 5.4 Requirement

Laravel 4.2 requires PHP 5.4 or greater. This upgraded PHP requirement allows us to use new PHP features such as traits to provide more expressive interfaces for tools like Laravel Cashier. PHP 5.4 also brings significant speed and performance improvements over PHP 5.3.

Laravel Forge

Laravel Forge, a new web based application, provides a simple way to create and manage PHP servers on the cloud of your choice, including Linode, DigitalOcean, Rackspace, and Amazon EC2. Supporting automated Nginx configuration, SSH key access, Cron job automation, server monitoring via NewRelic & Papertrail, "Push To Deploy", Laravel queue worker configuration, and more, Forge provides the simplest and most affordable way to launch all of your Laravel applications.

The default Laravel 4.2 installation's app/config/database.php configuration file is now configured for Forge usage by default, allowing for more convenient deployment of fresh applications onto the platform.

More information about Laravel Forge can be found on the official Forge website.

Laravel Homestead

Laravel Homestead is an official Vagrant environment for developing robust Laravel and PHP applications. The vast majority of the boxes' provisioning needs are handled before the box is packaged for distribution, allowing the box to boot extremely quickly. Homestead includes Nginx 1.6, PHP 5.6, MySQL, Postgres, Redis, Memcached, Beanstalk, Node, Gulp, Grunt, & Bower. Homestead includes a simple Homestead.yaml configuration file for managing multiple Laravel applications on a single box.

The default Laravel 4.2 installation now includes an app/config/local/database.php configuration file that is configured to use the Homestead database out of the box, making Laravel initial installation and configuration more convenient.

The official documentation has also been updated to include Homestead documentation.

Laravel Cashier

Laravel Cashier is a simple, expressive library for managing subscription billing with Stripe. With the introduction of Laravel 4.2, we are including Cashier documentation along with the main Laravel documentation, though installation of the component itself is still optional. This release of Cashier brings numerous bug fixes, multi-currency support, and compatibility with the latest Stripe API.

Daemon Queue Workers

The Artisan queue:work command now supports a —daemon option to start a worker in "daemon mode", meaning the worker will continue to process jobs without ever re-booting the framework. This results in a significant reduction in CPU usage at the cost of a slightly more complex application deployment process.

More information about daemon queue workers can be found in the queue documentation.

Mail API Drivers

Laravel 4.2 introduces new Mailgun and Mandrill API drivers for the Mail functions. For many applications, this provides a faster and more reliable method of sending e-mails than the SMTP options. The new drivers utilize the Guzzle 4 HTTP library.

Soft Deleting Traits

A much cleaner architecture for "soft deletes" and other "global scopes" has been introduced via PHP 5.4 traits. This new architecture allows for the easier construction of similar global traits, and a cleaner separation of concerns within the framework itself.

More information on the new SoftDeletingTrait may be found in the Eloquent documentation.

Convenient Auth & Remindable Traits

The default Laravel 4.2 installation now uses simple traits for including the needed properties for the authentication and password reminder user interfaces. This provides a much cleaner default User model file out of the box.

"Simple Paginate"

A new simplePaginate method was added to the query and Eloquent builder which allows for more efficient queries when using simple "Next" and "Previous" links in your pagination view.

Migration Confirmation

In production, destructive migration operations will now ask for confirmation. Commands may be forced to run without any prompts using the —force command.

Laravel 4.1

Full Change List

The full change list for this release by running the php artisan changes command from a 4.1 installation, or by viewing the change file on GitHub. These notes only cover the major enhancements and changes for the release.

New SSH Component

An entirely new SSH component has been introduced with this release. This feature allows you to easily SSH into remote servers and run commands. To learn more, consult the SSH component documentation.

The new php artisan tail command utilizes the new SSH component. For more information, consult the tail command documentation.

Boris In Tinker

The php artisan tinker command now utilizes the Boris REPL if your system supports it. The readline and pcntl PHP extensions must be installed to use this feature. If you do not have these extensions, the shell from 4.0 will be used.

Eloquent Improvements

A new hasManyThrough relationship has been added to Eloquent. To learn how to use it, consult the Eloquent documentation.

A new whereHas method has also been introduced to allow retrieving models based on relationship constraints.

Database Read / Write Connections

Automatic handling of separate read / write connections is now available throughout the database layer, including the query builder and Eloquent. For more information, consult the documentation.

Queue Priority

Queue priorities are now supported by passing a comma-delimited list to the queue:listen command.

Failed Queue Job Handling

The queue facilities now include automatic handling of failed jobs when using the new —tries switch on queue:listen. More information on handling failed jobs can be found in the queue documentation.

Cache Tags

Cache "sections" have been superseded by "tags". Cache tags allow you to assign multiple "tags" to a cache item, and flush all items assigned to a single tag. More information on using cache tags may be found in the cache documentation.

Flexible Password Reminders

The password reminder engine has been changed to provide greater developer flexibility when validating passwords, flashing status messages to the session, etc. For more information on using the enhanced password reminder engine, consult the documentation.

Improved Routing Engine

Laravel 4.1 features a totally re-written routing layer. The API is the same; however, registering routes is a full 100% faster compared to 4.0. The entire engine has been greatly simplified, and the dependency on Symfony Routing has been minimized to the compiling of route expressions.

Improved Session Engine

With this release, we're also introducing an entirely new session engine. Similar to the routing improvements, the new session layer is leaner and faster. We are no longer using Symfony's (and therefore PHP's) session handling facilities, and are using a custom solution that is simpler and easier to maintain.

Doctrine DBAL

If you are using the renameColumn function in your migrations, you will need to add the doctrine/dbal dependency to your composer.json file. This package is no longer included in Laravel by default.