Everything about Laravel 10: Deep Dive into the latest features of  Laravel 10

Everything about Laravel 10: Deep Dive into the latest features of Laravel 10

Exploring the features of Laravel 10 with support for PHP 8.1 by building a simple web application

In this article, we'll look into the new Laravel version which requires a minimum PHP version of 8.1 with a demo application.

if you're new to Laravel and will love to explore Laravel 9 Laravel 9: Building a blog application with Bootstrap 5

Laravel is the most widely used and popular PHP framework for building custom, robust, and scalable web applications.

The Laravel 10 was released on the 14th of February 2023 by the awesome Laravel team led by Taylor Otwell with minimum support for PHP 8.1.

Laravel v10 is the second TS(Long-Term Support) to be introduced following the 12 months release cycle and will be stable for 12 months until another release most likely in February or (Q1) 2024.

Here's the link to Laravel release note

In a bit to get on board with the new features in Laravel 10, we'll be building a simple application while discussing the features alongside.

Minimum PHP version support

Moving forward Laravel 10 supports PHP 8.1.12 as of the time of writing this and has dropped support for PHP8.0 and below.

Kindly follow the upgrade guide to PHP 8.1 as per your tools setup for Laravel

  • Upgrade the composer version because Laravel 10 requires Composer 2.2

If you've your path configured currently

composer self-update

To roll it back to the previous version use

composer self-update --rollback

Next, let's start with a fresh Laravel 10 app installation

laravel new laravel_10

OR

composer create-project laravel/laravel_10

After successful installation

In the composer.json file in the newly project created the PHP version is ^8.1 and the Laravel framework is ^10.0

Serve the application

php artisan serve

Wala! an amazing update to the default landing page!!!

Laravel v10.0.3 (PHP v8.1.12)

New Commands added

Previous commands in old version of Laravel

  • Run the composer global update on the CLI to update

      composer global update
    

    To view the list of newly added commands

      laravel help new
    

Native Type Declaration

Application skeleton and stub type-hints were contributed by Nuno Maduro.

What this simply means is that Laravel 10.x completely updates the application skeleton and all stubs used by the framework to add argument and return types to all method signatures. Also, unnecessary "doc block" type-hint data has been removed.

Existing applications that do not have these primitive type-hints will continue to function because the change is backward compatible with old applications.

Let's take a look at the Authenticate.php file in Laravel 10

    /**
     * Get the path the user should be redirected to when they are not authenticated.
     */
    protected function redirectTo(Request $request): ?string
    {
        return $request->expectsJson() ? null : route('login');
    }

You'll notice that the doc block has been updated

Return type added: ( null or string )

Type hint added: Request $request

Laravel Pennant

Laravel Pennant was developed by Tim MacDonald.

At the core of most applications is the addition of features as the development progresses either as MVP or a product. These features can be managed by the Laravel Pennant (a first-party package) which offers a light-weight, streamlined approach to managing application feature flags. Out of the box, Pennant includes an in-memory array driver and a database driver for persistent feature storage.

It doesn't come by default in a Laravel application so let's give it a try...

composer require laravel/pennant

Next, publish the Pennant configuration using vendor:publish Artisan command:

php artisan vendor:publish --provider="Laravel\Pennant\PennantServiceProvider"

Finally, run the php artisan migrate for the database migrations. This will create a features table that Pennant uses to power its database driver.

php artisan migrate

Introduced in Laravel 10 is the automatic creation of a database if it does not exist.

Head over to the AppServiceProvider file to create a new feature using the define method.

        //ui-design is the new feature to implement
        Feature::define('ui-design', function (User $user){
            //we can specify the user that can see the new ui design feature
            //for this feature a customer can view the ui design
            return $user->isCustomer();

        });

The isCustomer method is created in the User model file to allow users to view the new feature

    public function isCustomer(){
//if the logged in user id is 1 or 2 allow them to view the new ui
        return in_array($this->id, [1, 2]);
    }

Next, Uncomment the User factory in the Database seeder file to help us seed some dummy users

        \App\Models\User::factory(10)->create();

Run the db:seed

php artisan db:seed

In the routes file let's authorize a user with Id 1 to view the new ui design feature.

//Test for Laravel Pennant
auth()->onceUsingId(1);

Route::get('/', function () {
    return view('welcome');
});

@feature blade directives are available for use in the view files for convenience.

Let's display a view for a customer with active access to the ui-design feature

    <!-- the feature blade directive can be used to display an interface if the new ui is active for the current user -->
    @feature('ui-design')
    <div class="mt-16">
        <div>
            <a href="https://laravel-news.com" class="scale-100 p-6 bg-white dark:bg-gray-800/50 dark:bg-gradient-to-bl from-gray-700/50 via-transparent dark:ring-1 dark:ring-inset dark:ring-white/5 rounded-lg shadow-2xl shadow-gray-500/20 dark:shadow-none flex motion-safe:hover:scale-[1.01] transition-all duration-250 focus:outline focus:outline-2 focus:outline-red-500">
                <div>
                    <h2 class="mt-6 text-xl font-semibold text-gray-900 dark:text-white">Laravel Pennant view for customer 1</h2>

                    <p class="mt-4 text-gray-500 dark:text-gray-400 text-sm leading-relaxed">
                        Laravel Pennant is now added via the ui-design feature
                    </p>
                </div>
            </a>
        </div>
    </div>

    @endfeature

Refresh the landing page to see the new feature active for the current user

Since the user with ID 1 is allowed to view the feature, the scope value is set to true on the features table.

change the user id to 3 and the feature display will be inactive for the current user.

//Test for Laravel Pennant

auth()->onceUsingId(3);

Route::get('/', function () {
    return view('welcome');
});

The features table gets updated.

Refresh the page and the new feature is not active for the current user to view.

To activate a new customer for the current scope use the activate method with the name of the feature

//Test for Laravel Pennant

auth()->onceUsingId(3);

Route::get('/', function () {
    Feature::activate('ui-design');
    return view('welcome');
});

Also once a feature has been defined, you may easily determine if the current user has access to the given feature:

if (Feature::active('new-onboarding-flow')) {
    // ...
}

For more information, please consult the comprehensive Pennant documentation.

Process layer for Laravel

The process abstraction layer was contributed by Nuno Maduro and Taylor Otwell.

With the new awesome abstraction layer, Laravel can initiate and interact with external processes via the new Process facade:

Let's give it a try

use Illuminate\Support\Facades\Process;


Route::get('/process', function () {

    //in macos / linux
    $result = Process::run('ls -la');

    // in windows os
    $result = Process::run('dir');

    // this will output the list of files in the current direct
    return $result->output();

    // other methods on the process facade
    $result->successful();
    $result->failed();
    $result->output();
    $result->exitCode();
    $result->errorOutput();
    $result->throw();
});

Output

  • Other stuff can be done while another process is still running.

  • You can also fake the process command using the Process::fake().

Process::fake();

// ...

Process::assertRan('dir');

For more info look up the Process section in the documentation

Test profiling

Test profiling was contributed by Nuno Maduro.

The --profile is the new flag added to the Artisan test command that allows you to easily identify the slowest tests in your application

Generator CLI Prompts

Generator CLI prompts were contributed by Jess Archer.

Prompt for required arguments in all of Laravel's built-in make commands is a great improvement to the developer experience if the commands were invoked without input.

php artisan make:controller

Horizon / Telescope Facelift

Horizon and Telescope have been redesigned with a fresh, modern look including improved typography, spacing, and design

All Validation Rules Invokable by Default

The invokable validation rule can now be made without specifying --invokable flag in Laravel 10.

php artisan make:rule SignUpRule

New Password generator Helper method

The new Str password helper can be used to generate a custom password with arguments for customizing password length (as opposed to the default 32 lengths) characters, symbols, numbers, and alphabet combinations.

public static function password($length = 32, $letters = true, $numbers = true, $symbols = true, $spaces = false)

We'll use the routes page to try out this implementation using the short helper form.

Route::get('/password', function() {
    return str()->password();
});

outcome -->
y084ycjP93i*Dc8,C.$-ER#b.SE5eOJR

It can be customized to return 12 character length password without a number.

Route::get('/password', function() {
    return str()->password(12, numbers: false);
});

Output --> 
B>V(&L?B*MJh

Pest Scaffolding

The --pest flag can be used to create a new Laravel project with Pest test scaffolding by default.

laravel new laravel_10 --pest

Scaffolding with Breeze (to add authentication feature) can also be achieved by adding the --breeze flag and so forth as per the project requirement.

Modification of database column

Previously to modify a database column the doctrine/dbal package has to be required. But in Laravel 10 with the change() method database column can be modified.


$table->integer('address')->nullable();

//to change it to a string in Laravel 10

$table->string('user_balance')->change()

Tutorial Code Repository

Conclusion

Laravel 10 is super cool and packed with new features to make the developer experience beautiful while building robust applications. It also ships with support for Vite and new commands, password hashing etc.. is way faster than previous Laravel versions.

Twitter: Alemsbaja | Youtube: Tech with Alemsbaja to stay updated on more articles

Find this helpful or resourceful?? kindly share and feel free to use the comment section for questions, answers, and contributions.

Did you find this article valuable?

Support Alemoh Rapheal Baja by becoming a sponsor. Any amount is appreciated!