Laravel 8, the brand new release of the Laravel framework is all set to launch on 8th of September. Taylor Otwell gave an impressive insight of what to expect in this year’s Laracon Online. Due to the pandemic, over 5k developers attended it from home and watched the Live Webinar, making it the largest Laracon ever. It was packed with some amazing presentations, and the Monstar Lab PHP Team was lucky to also be part of that conference.

Here is a quick rundown of all the features that are set to ship in Laravel 8. Details of the features will soon be out in the new Dark Mode enabled Laravel site. The addition of dark mode is also a new feature of its own for the developers to enjoy.

Small disclaimer: I might misunderstood some features while listening to the one hour presentation. But once the documentation is up, I will revisit this article and update accordingly.

Features:

  1. App/Models is now default:

    artisan make:model Foo

    This command will now create Foo Model in the app/Models folder. If developers decide to delete the app/Models folder, and run the above command again, Laravel will understand that app/Models folder doesn’t exist and hence will create a Foo model in the root folder. This feature was a great addition by Taylor after he ran a poll on Twitter, to know the community’s preference.

    Once deleted app/Models folder, the artisan command will make the Foo model in root like app/Foo.php

  2. No more magic prefixes in namespaces:

    Route::get('/foo', 'FooController@index')

    When FooController was declared, behind the scenes App\Http\Controlllers\FooController was added by the RouteServiceProvider using this function:

    protected function mapWebRoutes()
    {
        Route::middleware('web')
             ->namespace($this->namespace)
             ->group(base_path('routes/web.php'));
    }
    

    But now, namespace property is trashed by default, so that if someone writes:
    Route::get('/foo', '\App\Http\Controlllers\FooController@index') It won’t cause magic prefix to be added.

  3. Route Closures can now be cached:

    Usually when route caching is enabled, a serialized output of the routes file is generated, i.e. all is compiled into a big php array. Currently routes that are defined like in the example below couldn’t be cached.

    Route::get('foo', function () {
        return 'Hello World';
    });
    

    Now closures can also be cached.

  4. Extended component enhancement:

    Nested component attributes are now allowed to be merged.

    public render()
    {    return <<<'HTML'
        <x-button { $attributes->merge(['class' => 'bg-red']) }>
            { $slot }
        </x-button>
        HTML;
    }
    
  5. Registering event listener syntax improvement:

    We usually do this register event listener:

    /**
     * The event listener mappings for the application.
     *
     * @var array
     */
    protected $listen = [
        'App\Events\SomeEvent' => [
        'App\Listeners\EventListener',
        ],
    ];
    

    Now, we do not need to repeat class names, rather it is type-hinted:

    
    Event::listen(SomeEvent::class, function(SomeEvent $event) {
        info($event->whatever)
    });
    
    Event::listen(function (SomeEvent $event) {
        info(get_class($event))
    });
    
    
  6. Addition of queuable anonymous event listeners

    We can queue Model events now in Models:

    //in Foo Model Class
    
    protected static function booting()
    {
        static::created(queuable(function (Foo $foo){
            info('Queued: ' $foo->name);
        }))
    }
    
  7. Secret maintenance mode

    artisan down —secret=laracon-2020

    IP whitelisting is very difficult. Now we can access route as secret. During maintenance mode, when the server is down, using the command mentioned above we can start accessing the application and routes. This will be valid for several hours even in maintenance mode. There will be several options available in the artisan down command like: render, redirect, status and secret to ensure much more control.

  8. New catch method for anonymous queue function:

    There is a new catch method for anonymous queue function. Initially it went to failed jobs, now we can have a callback to catch that.

    Route::get('/queue-catch', function(){
        dispatch(function() {
            throw new Exception('Something went wrong...');
        })->catch(function (Throwable $e) {
            info('Caught exception');
        });
    
        return 'Dispatched';
    });
    
  9. Exponential backoff job class:

       BackoffJob::dispatch();
    

    We can now exponentially increase backoff retries, using a simple declaration:

       public function backoff()
       {
         return [1, 5];
       }
    
  10. Job Batching:

    Job Batching, has been modelled after Ruby’s Sidekiq. Now we can queue a bunch of jobs that triggers at the same time, and then it will trigger callbacks after the entire batch is finished.

     Bus::batch([
         new BatchedJob,
         new BatchedJob,
         new BatchedJob,
         new BatchedJob,
         new BatchedJob,
     ])->then(function (Batch $batch) {
            info('All Jobs completed Successfully');
     })->catch(
            info('First Batch job failure detected');
     )->finally(
            info('The batch has finished executing');
     )->dispatch();
    

    Failed items also can be caught without interuption.

    Real time progress can be seen of this batched jobs:

    Bus::findBatch('<id of the batch>')
    
  11. Rate limiting improved:

    New global rate limiting facade (like auth gates) is introduced:

    ['throttle:global'], ['throttle:nested'],
    
    // in configure functions
    Limit::perMinute(100);
    Limit::perMinute(3)->by($request0->input('email'));
    
  12. Custom Exceptions:

    Report and render methods can be ditched and there is a new way of declaring custom exceptions:

    $this->reportable(function (AppException $e) {
        info('error');
    })->stop();
    
    $this->renderable(function (AppException $e) =>  );
    
  13. Squash migrations:

    artisan schema:dump

    This will now generate the entire existing migration into a schema file. After running this command, if we run any new migrations, we can then again run the same command. This will then generate a new one into a single new migration. It is basically for development mode, like one file with 50 migrations squashed.

  14. Factories are re-written:

    They are class based and they are like factories on steroids, pretty much everything can be done, like creating data with relationships, for one specific id, etc. A short note for the functions are given below:

    // new  definition function
    public function definition()
    {
        return [
            'name' => blah blah
        ]
    }
    
     // same
    Foo::factory()->create(),
    Foo::factory()->create([]);
    
    // custom functions
    Foo::factory()->withStatus('draft')->create()
    // which is:
    public function withStatus()
    {
        return $this->state(fn ($attributes) =>
        ['status' => ''];
    )};
    
    //relationships of all kinds can be used in factory
    Foo::factory()
    ->times(3)
    ->has(Bar::factory()
        ->times(3)
        ->state('draft'))
    ->create()
    ->load('fooBar');
    

    Legacy factory package will be available to support existing ones.

  15. Laravel JetStream:

    Free package, it is more that any general auth scaffolding. Laravel JetStream can be used with Livewire/Inertia, and has several big punches in store to woo the developer crowd for sure.

I hope you enjoyed this quick rundown of the new features. Huge shout out to the entire community for the tweets, you can follow most here at LaraconOnline. Feel free to poke me @saadbinamjad if I missed any features. Till then, happy coding folks!

Author

Saad Bin Amjad

Technical Lead

Prefers tea over coffee, and coffee over anything else. Loves to code/speak.

You may also like

Make apps for everyone

The human brain tends to assume that everybody else thinks and behaves in a similar way to it. So every person tends to think that, based on certain categories, they’re part of a majority, that there are many others like them. As software developers, it’s very easy to assume that...

Locust sketch

Locust is an easy-to-use distributed load testing tool that is completely event-based, that is, a locust node can also support thousands of concurrent users in a process, without callbacks, and use a lightweight process through gevent (that is, in Run in its own process). And has the following characteristics:

QA