Victor Jonah I am a Software Developer with over 3 years of experience working with JavaScript and its frameworks. I currently work as a remote Software Developer for a tech agency.

Laravel vs. AdonisJs: Which should you use?

5 min read 1561

Adonis and Laravel logos.

Laravel, a popular MVC (model view controller)-based framework has everything and anything you might need to create a web application. It’s got you covered when it comes to authentication, routing, database migrations, models, helpers and more. However, this might be overkill for small or simple applications.

On the other hand, AdonisJs is also an MVC-based framework built on top of Node.js. Additionally, it’s highly focused on developer ergonomics, stability, and confidence. It is based on the same concepts as Laravel. Inspired by Laravel, same goodies such as Providers and Dependency Injection allow for better flexibility and organization of your code.

In this article, we will make a comparison between Laravel and AdonisJs. We will analyze the setup, view, ORM, routing, database, CLI, IOC and service providers, file system, community strengths, and performance of each framework.

Setup

Laravel installation is easy. Use Homestead — a development environment — and every requirement is settled. However, if you do not want to use Homestead, you will have to make sure your server supports a few of its requirements. These include the Tokenizer PHP Extension, PDO PHP Extension, JSON PHP Extension, and more.

laravel new will create a fresh new installation in the directory you specify:

laravel new project

Or, you can create a new installation via Composer Create-Project:

composer create-project --prefer-dist laravel/laravel project

Laravel allows for free configuration and does not force a project structure, which makes it flexible. Once installed, you can run your application using the following command:

php artisan serve

Adonis is also easy to set up. Installation is done via Adonis CLI, a tool to help you install or run Adonis commands. The CLI must be installed globally first:

npm i -g @adonis/cli

Once installed, you can use the adonis new command to make a new installation in the directory you specify:

adonis new project

Another alternative is via Git, which has to do with you cloning the repo from Github: API-only, full-stack, and slim boilerplates.

We made a custom demo for .
No really. Click here to check it out.

Once installed, you start your application and start developing:

adonis serve --dev

Views

Laravel has a powerful template engine called Blade. It is quite similar to Twig. The real deal comes from using PHP code directly inside your view, meaning Blade views compiled to PHP code are processed in the server when a request is made:

<!-- Stored in resources/views/layouts/app.blade.php -->

<html>
    <head>
        <title>App Name - @yield('title')</title>
    </head>
    <body>
        @section('sidebar')
            This is the master sidebar.
        @show

        <div class="container">
            @yield('content')
        </div>
    </body>
</html>

Adonis comes with the Edge templating engine, which is super fast. It supports runtime debugging in Chrome DevTools, physical tags for text importance with logical tags, layouts and partials, and Components-style. Just like Blade, you can also write your JavaScript inside your view:

@if(hours < 12)
  <h2> Good Morning </h2>
@elseif(hours < 18)
  <h2> Good Afternoon </h2>
@else
  <h2> Good Evening </h2>
@endif

ORM

Laravel comes with the Eloquent ORM, which observes the Active Record Pattern. This, unlike plain database queries, provides efficient and powerful APIs to drive your application’s data flow. It is loved for its organization of the application’s database. It also supports the most popular databases(MySQL, Postgre, SQLite, etc).

Create an Eloquent Model, which communicates to your database table. Models allow you to interact with a table either by insert or query.

We create our model faster by using the artisan command:

php artisan make:model User

In the model, you can set your conventions and so on.

Creating a user works like this:

<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\Request;

class UserController extends Controller
{
    /**
     * Create a new user instance.
     *
     * @param  Request  $request
     * @return Response
     */
    public function store(Request $request)
    {
        // Validate the request...

        $user = new User;

        $user->name = $request->name;


        $user->username = $request->username;


        $user->email = $request->email;


        $user->password = $request->password;

        $user->save();
    }
}

One beautiful thing is its API to manage relationships:

return $this->hasOne('App\Models\Phone', 'foreign_key');

Adonis comes with the Lucid ORM, which also uses the active record pattern. It comes with date format management, lifecycle Hooks for things like password hashing, data serialization, getters/setters for data transformation, and more.

Creating a model is almost the same as Eloquent ORM. Conventions also come in handy, if needed:

adonis make:model User
'use strict'

const Model = use('Model')

class User extends Model {
}

module.exports = User

Creating a user is no different from Eloquent ORM:

const User = use('App/Models/User')

const user = new User()

user.username = 'virk'
user.password = 'some-password'

await user.save()

It also has an expressive API to manage relationships.

hasOne(relatedModel, primaryKey, foreignKey)

Routing

Like Laravel, Adonis accepts a basic route file as URL and a Closure, which is a pretty simple way of defining a route:

Route.get('posts/:id', ({ params }) => {
  return `Hello  ${params.id}`
})

The other most-used way to enable routing is by plugging your Controllers into your endpoints in a route file. The route file is under your start folder, unlike Laravel, which is stored in the root folder of the project.

Laravel

Route::get('/user', [UserController::class, 'index']);

AdonisJs

Route.get('users', 'UserController.index').as('users.index')

Both frameworks also group endpoints and assign HTTP verbs associated to the endpoint.

Laravel

Route::prefix('admin')->group(function () {
    Route::get('users', function () {
        // Matches The "/admin/users" URL
    });
});

AdonisJs

Route.group(() => {
  Route.get('users', closure)   // GET /api/v1/users
  Route.post('users', closure)  // POST /api/v1/users
}).prefix('api/v1')

Database

Currently, Laravel supports 4 databases: MySQL, PostgreSQL, SQLite and SQL Server. All configurations for your database are located at config/database.php. Database connections are defined in this file, including what should be the default.

Migrations, which are like version control, are supported in Laravel. This convention allows the writing of data model changes.

Just like Laravel, AdonisJs supports migrations and seeding. Seeding helps to test your tables with data.

AdonisJs supports six databases, which are MySQL, PostgreSQL, MariaDB, SQLite3, MSSQL, and Oracle.

CLI

AdonisJs and Laravel come out of the box with their own CLI. This allows developers to run commands for specific tasks, from running migrations, generating controllers, models, and seeding databases to creating your own commands.

Laravel’s command tool is called Artisan, while the AdonisJs command tool is Ace.

IOC and service provider

Dependencies are hard to manage in any application. They can either be independent or dependent. If not handled properly, they might cause bugs. Adonis solves that problem using IoC, while Laravel calls it Services Container, which typically manages class dependencies and performs dependency injections.

Service Providers handles registering of middlewares, event listeners, routes and service container bindings. Most of the time, you will be registering your middlewares for usage in your application. This pattern goes for both Laravel and AdonisJs.

File system

AdonisJs uses its dedicated Drive Provider (which has to be registered in the Service Provider) called FlyDrive. This helps in the interaction of the local and remote file systems, like Amazon S3.

Pulling our drive from npm is a must, as it is not installed by default:

adonis install @adonisjs/drive

Next, we register it in our service provider:

const providers = [<br> '@adonisjs/drive/providers/DriveProvider'<br>]

Laravel uses FlySystem as its API, and is even flexible to switch between local and remote file systems(Amazon S3) as the API remains the same.

Community strength

AdonisJs has a weak community as of now, meaning it is pretty small. This alone results in less contributors and few answers on StackOverflow. Most issues can never be found, so you may have to dig deep.

Meanwhile, both frameworks’ documentations are great and well explained. They cover everything, and are very helpful to experienced and new developers.

Performance

Both Laravel and AdonisJs are super fast, and in most cases your web application will be fast when deployed to the server. If you feel your applications has a slow response time, there is no need for comparison. Instead, work on the following below:

  • Remove unused packages
  • Use the latest version of AdonisJs or Laravel
  • Cache router
  • Cache configuration file
  • Cache views
  • Reduce or make the views less.
  • Use eager loading
  • Index mostly used database table columns
  • And many more optimization tips

With all these, we won’t be having a performance comparison.

Conclusion

In this article, we looked at the basic differences between Laravel and AdonisJs and highlighted their best features. Overall, neither is really better than the other — they both achieve the desired goal, it all depends on your use case.

Also, keep in mind that similarities range from routing, migration, models, controllers, middlewares, configuration files, and .env. Outside that, both are fast and performant on the same scale.

For Node.js developers, AdonisJs might be an interesting MVC tool to use. For those wanting to migrate from PHP to Node.js, then AdonisJs is the right choice.

It would be good to remember that both frameworks are robust and can solve problems that need to be solved. Both are also open source.

200’s only Monitor failed and slow network requests in production

Deploying a Node-based web app or website is the easy part. Making sure your Node instance continues to serve resources to your app is where things get tougher. If you’re interested in ensuring requests to the backend or third party services are successful, try LogRocket. https://logrocket.com/signup/

LogRocket is like a DVR for web apps, recording literally everything that happens on your site. Instead of guessing why problems happen, you can aggregate and report on problematic network requests to quickly understand the root cause.

LogRocket instruments your app to record baseline performance timings such as page load time, time to first byte, slow network requests, and also logs Redux, NgRx, and Vuex actions/state. .
Victor Jonah I am a Software Developer with over 3 years of experience working with JavaScript and its frameworks. I currently work as a remote Software Developer for a tech agency.

Leave a Reply