James James James is a student software developer at Oppia Foundation.

Laravel Livewire vs. Vue

4 min read 1383

Laravel Livewire vs. Vue

There used to be two ways to build the frontend for a Laravel application: either use a frontend framework, such as React or Vue, or work from a Blade template.

Now there is a third option: Laravel Livewire.

Livewire is a full-stack framework that streamlines the process of building dynamic interfaces in Laravel. Basically, it enables you to do things within the confines of Laravel that would have previously required JavaScript.

In this guide, we’ll compare Livewire to Vue.js and explore some key features to help you decide which to use in your next project.

Prerequisites

To follow along with this tutorial, you’ll need:

  • Some knowledge of Vuejs 2.x
  • Knowledge of Laravel
  • Experience using Blade to make templates

Setup

It’s fairly easy to set up Vue in a Laravel application. From Laravel 7, you can use the laravel/ui package to set up Vue as well as other frontend frameworks, such as React and Bootstrap.

The command below will install laravel/ui in a Laravel project.

composer require laravel/ui

After installing the package, set up Vue by running the artisan command.

php artisan ui vue

Similarly, Livewire is a PHP package that is installed using Composer.

composer require livewire/livewire

Livewire provides some Blade directives — @livewireScripts and @livewireStyles — which are used to add Livewire-related scripts and styles, respectively. The Livewire directives are just custom Blade directives and are rendered on page load.

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

Components and templating

A component is a reusable piece of the user interface. Each framework handles components differently.

A simple Livewire component is a PHP class that extends the Livewire component class and renders a Blade file.

<?php
namespace App\Http\Livewire;
use Livewire\Component;
class Post extends Component
{
    public function render()
    {
        return view('livewire.post');
    }
}

This is what a simple Livewire component looks like — and yes, it does look a lot like a Laravel controller, which returns a view. Just as in a Laravel controller, the Blade template for this component can be found at resources/views/livewire/post.blade.php.

Livewire also has inline components, which use Blade inline templates. The render function for a Livewire inline component looks like this:

public function render()
{
    return <<<'blade'
        <div>
            {{-- Do your work, then step back. --}}
        </div>
    blade;
}

Livewire inline components can only be used in PHP versions 7.3 and above, which now have support for flexible heredoc.

In Livewire, you can access any feature that’s available in Laravel Blade. You have direct access to items such as the CSRF token (@csrf) and the currently authenticated user (@auth) with all the available guards.

There are two types of components you can create in Vue: single-file and global components.

Single-file components are written in .vue files. They share many similarities with plain HTML and offer you different sections to write templates, styles, and scripts.

<template>
  <h2>Hello World</h2>
</template>

<style>
h2 {
  color: red
}
</style>

<script>
export default {
};
</script>

Global components are created from the Vue module.

const Vue = require('vue');

Vue.component("hello-world", {
  template: '<h2>Hello World</h2>'
});

The global component is significantly different from SFC in that HTML is written as template strings and passed in an object as the second argument to Vue.component. The first argument is the name of the component. Components created this way are globally available throughout the Vue application.

Accessing data

There is no application without data, and handling data is an important factor to consider when choosing a frontend framework. Again, each framework tackles the data problem differently.

Vue components do not have direct access to the data from the backend. They depend on an API to fetch the data to be rendered by a component.

This approach has its pros and cons. The obvious problem is that of increased initial render time: since the data to be displayed is not immediately available to the component, it will take more time to request to fetch the data. This is especially true for users with a poor internet connection. One solution is to render your component beforehand. Methods such as server-side rendering and prerendering are available in Vue. A benefit of rendering the data on the client is that your component can fetch data only when it needs to. A component that is not rendered will not need to fetch data.

Livewire components, on the other hand, are rendered by default on the server. They have direct access to the backend data and do not need to make an extra request to fetch the data. Since they are Blade templates, these components have access to Laravel’s authorization directive and can render a different template based on the user’s permissions. The disadvantage is that, since the rendering is done on the server, the component has to be rendered every time it is required, which can lead to an increase in the time to the first byte. To solve this problem, you can cache the component after it has been rendered. However, for some dynamic pages, the components will need to be rerendered anyway.

Reactivity

Modern web applications are dynamic and change based on user interaction. As such, it’s important to choose a framework that’s capable of handling reactivity is important.

Laravel and Vue handle reactivity differently depending on the location of the application state.

Vue approaches reactivity in a very simple way: by tracking the changes to specific variables and rerendering the affected parts of the DOM. When creating Vue components, you define variables for Vue to track (reactive data). Below is a simple component with one reactive variable, message.

<template>
    <h2>{{ message }}</h2>
</template>
<script>
export default {
    data() {
        return {
            message: "Hello World!"
        };
    }
};
</script>

In the above component, Vue tracks every change made to message and will update the h2 appropriately. However, these updates happen on the client (browser) and do not need to interact with the backend for any reason because the state of this component lives in the browser.
For some dynamic applications, the state needs to be in sync with the data in the database. An ajax will update the backend with the change in the state. If the update to the backend fails, the frontend will have an updated state while the backend has a different state, which can lead to a state of confusion in the application.

By contrast, the state of a Livewire component resides on the server. This has its advantages and disadvantages.

<?php
namespace App\Http\Livewire;
use Livewire\Component;
class HelloWorld extends Component
{
    public $message = 'Hello World';
    public function render()
    {
        return <<<'blade'
            <div>
                {{ $message }}
            </div>
        blade;
    }
}

For simple components like the above, there is no effect of the state being stored on the server. However, for dynamic components that update frequently based on user interaction, several ajax requests have to be made to update the state in the server.

This might introduce some lag in the rendering of the page because the ajax request is not yet complete before the next action is performed. This is an issue that Livewire is aware of. The official docs offer some methods to help reduce this delay when updating the UI.

Having the application state in the server for some dynamic applications helps maintain a single source of truth. Also, since the Livewire component is very close to the backend data, the data can be validated before being rerendered to the page.

Conclusion

In this guide, we explored the differences between Laravel and Vue and highlighted areas in which they both shine. Neither framework is significantly better than the other; it all depends on your use case.

For applications with a lot of reactivity, Livewire might not be the best framework for you. However, if your application relies a lot on data from the database, has minimal reactivity, and needs to load as fast as possible, you might want to give Livewire a shot.

The Livewire concept is currently used in applications such as GitHub and Hey. These platforms do not have much in the way of reactive components but can maintain a really fast interface.

Experience your Vue apps exactly how a user does

Debugging Vue.js applications can be difficult, especially when there are dozens, if not hundreds of mutations during a user session. If you’re interested in monitoring and tracking Vue mutations for all of your users in production, try LogRocket. https://logrocket.com/signup/

LogRocket is like a DVR for web apps, recording literally everything that happens in your Vue apps including network requests, JavaScript errors, performance problems, and much more. Instead of guessing why problems happen, you can aggregate and report on what state your application was in when an issue occurred.

The LogRocket Vuex plugin logs Vuex mutations to the LogRocket console, giving you context around what led to an error, and what state the application was in when an issue occurred.

Modernize how you debug your Vue apps - .

James James James is a student software developer at Oppia Foundation.

Leave a Reply