Software Testing & QA Services

Inertia.js and its advantages for Laravel developers

December 20, 2021

Tags: Technologies, IT Staff Augmentation
laravel
Unsplash

 

 

Inertia.js allows you to create single page applications without the need to build an API. It is not tied to Laravel or Vue but does offer an adapter for these two frameworks. Inertia does not depend on any technology, but it is very similar in its use to Laravel, so expert developers in the latter have Inertia.js among their favorites.

 

Inertia is not a framework, nor is it a replacement for your existing server-side or client-side frameworks. Rather, it is designed to work with them. Think of Inertia as a glue that connects the two. Inertia does this through adapters.

 

How to use Inertia in Laravel

 

As a new approach to creating classic server-driven web applications, this is how developers are defining Inertia. The library allows its users to render single file Vue components from the Laravel backend.

 

This allows you to create single page applications, SPAs, fully rendered on the client side without the high complexity associated with these types of pages today.

 

laravel

 

Inertia works like a classic server-side rendered application: controllers, database operations, and views are written as before, and JavaScript page components now replace views. In the case of Laravel, Inertia uses existing authentications, does not require development of the entire API, and sheet views are replaced with JavaScript components.

 

Advantages and disadvantages of Inertia

 

Among the advantages that Inertia offers to Laravel users are:

 

  • The application paths are all contained in a single file.
  • Inertia completely eliminates the complexity of client-side routing.
  • It is possible to configure it with React.

 

Among the disadvantages, it presents:

 

  • The developer using Inertia must have knowledge of both PHP and Vue.
  • If the intention is to create an app for Android or iOS, the backend API must be recreated.
  • It has very limited usability without Vuex.

 

Laravel Breeze also offers an Inertia.js frontend implementation powered by Vue or React. To use an Inertia stack, specify vue or react as your desired stack when executing the breeze:install Artisan command:

 

php artisan breeze:install vue

// Or...

php artisan breeze:install react

npm install
npm run dev
php artisan migrate

 

Another features of Laravel

 

User online or offline on Laravel

 

One of the most sought after features in networks by experts in this framework is how to know if a user is online or offline. Let's go step by step:

 

First configure the database

 

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=Enter_Your_Database_Name
DB_USERNAME=Enter_Your_Database_Username
DB_PASSWORD=Enter_Your_Database_Password

 

The next step is to install auth and then add a column in the users table

 

php artisan make:migration add_last_seen_to_users_table --table=users

 

Successfully run the above command after adding the column in the users table. Open the migration file and put the code below.

 

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class AddLastSeenToUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->timestamp('last_seen')->nullable();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->timestamp('last_seen');
        });
    }
}

 

Create Middleware

 

php artisan make: middleware LastSeenUserActivity

 

Then open the LastUserActivity.php file and paste the following code:

 

<?php

namespace App\Http\Middleware;

use Closure;
use App\User;
use auth;
use Cache;
use Carbon\Carbon;

class LastSeenUserActivity
{
    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if (Auth::check()) {
            $expireTime = Carbon::now()->addMinute(1); // keep online for 1 min
            Cache::put('is_online'.Auth::user()->id, true, $expireTime);

            //Last seen
            User::where('id', Auth::user()->id)->update(['last_seen' => Carbon::now()]);
        }
        return $next($request);
    }
}

 

Then add middleware to the kernel file

 

protected $middlewareGroups = [
    'site' => [
        \App\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        // \Illuminate\Session\Middleware\AuthenticateSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \App\Http\Middleware\VerifyCsrfToken::class,
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
        \App\Http\Middleware\LastSeenUserActivity::class,
    ],

    'api' => [
        'throttle:60,1',
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
    ],
];

 

Add the route

 

Route::get('/status', 'UserController@show')

 

Create the controller

 

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\User;
use Cache;
use Carbon\Carbon;

class UserController extends Controller
{
    public function show()
    {
        $users = User::all();
        return view('status', compact('users'));
    }
}

 

Create View File

 

@extends('layouts.app')

@section('content')
    <div class="container">
        <div class="row justify-content-center">
            <div class="col-md-8">
                <div class="card">
                    <div class="card-header bg-info text-white text-center"><h2><b>How to Check User Online Status & Last Seen in Laravel - NiceSnippets.com</b></h2></ div>
                    <div class="card-body">
                        @php $users = DB::table('users')->get(); @endphp
                        <div class="container">
                            <table class="table table-bordered">
                                <head>
                                <tr>
                                    <th>Name</th>
                                    <th>Email</th>
                                    <th>Status</th>
                                    <th>Last Seen</th>
                                </tr>
                                </thead>
                                <tbody>
                                @foreach($users as $user)
                                    <tr>
                                        <td>{{$user->name}}</td>
                                        <td>{{$user->email}}</td>
                                        <td>
                                            @if(Cache::has('is_online' . $user->id))
                                                <span class="text-success">Online</span>
                                            @else
                                                <span class="text-secondary">Offline</span>
                                            @endif
                                        </td>
                                        <td>{{ \Carbon\Carbon::parse($user->last_seen)->diffForHumans() }}</td>
                                    </tr>
                                @endforeach
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
@endsection

 

And that's it, so you can see if the user is online or offline.

 

The developers at Rootstack have used Laravel to solve various technological problems of our regional and international clients. If you want to belong to a multicultural team focused on creating the technologies of the present and future, apply here and let us know your talent.

 

We recommend you on video


 

Let's work together!