Elvis Miranda

Elvis Miranda

1558604896

Advanced Server-Side Rendering With Laravel & Vue

Now I want to build on that previous tutorial and demonstrate how to server render a Vue app that includes multiple pages with Vue Router, since most of your Laravel projects will have more than one page.

You can get the completed code for this tutorial here on Github.

Note: this article was originally posted here on the Vue.js Developers blog on 2017/11/27### Installation

This tutorial will extend the app I built in the previous article, Server-Side Rendering With Laravel & Vue.js 2.5. Make sure you’re familiar with how it works and have a suitable development environment set up i.e. with the php-v8js extension installed.

If you don’t have that code, clone it and set it up:

$ git clone https://github.com/anthonygore/vue-js-laravel-ssr
$ cd vue-js-laravel-ssr
$ cp .env.example .env
$ composer install
$ npm i

Then install Vue Router:

$ npm i --save-dev vue-router

Router module

We’ll begin by creating a file for our router configuration that exports an instance of the router for use in the app.

I’ve made up some sample routes with each displaying a component generated from the method pageComponent. This factory method returns a simple component that does nothing more than display the name of the page. This is all we need to prove SSR routing works.

resources/assets/js/router.js

import Vue from 'vue'
import Router from 'vue-router'
Vue.use(Router);
function PageComponent(name) {
 return {
   render: h => h('h3', `Hello from the ${name} page`)
 };
}
export default new Router({
  mode: 'history',
  routes: [
    { path: '/', component: PageComponent('Home'), name: 'home' },
    { path: '/about', component: PageComponent('About'), name: 'about' },
    { path: '/contact', component: PageComponent('Contact'), name: 'contact' }
  ]
});

router.js

In the main app file we’ll now import the router module and add it to the app, just as you would in any Vue project. The app instance is then exported for use in the client and server entry files.

resources/assets/js/app.js

import App from './components/App.vue';
import Vue from 'vue';
import router from './router'
export default new Vue({
  router,
  render: h => h(App)
});

app.js

Laravel routes

Note that our Vue Router instance is in history mode, so routes will fallback to the server when a sub-page is refreshed or loaded from the navigation bar.

This means that any route that we created in the front-end app also needs to be created on the server side. They can all point to the same controller method get:

routes/web.php

<?php
Route::get('/', 'AppController@get');
Route::get('/about', 'AppController@get');
Route::get('/contact', 'AppController@get');

web.php

Controller

Now we need to set up multi-page SSR in the controller. This is a modification of the logic in the base app, so make sure you’re familiar with how that worked.

To SSR a multi-page app, we need to tell the Vue server app (as defined in entry-server.js) what the current URL being requested is. This will ensure that when the app loads in the sandbox, it’s displaying the correct page component.

To do this we pass the URL i.e. $request->path() through to the render method from the get method. We then store the URL in a global JavaScript variable url that will be accessible from the Vue server app when it runs in the sandbox.

app/Http/Controllers/AppController.php

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\File;
use Illuminate\Routing\Route;
class AppController extends Controller
{
  private function render($path) {
    $renderer_source = File::get(base_path('node_modules/vue-server-renderer/basic.js'));
    $app_source = File::get(public_path('js/entry-server.js'));
    $v8 = new \V8Js();
    ob_start();
    $js = 
<<<EOT
var process = { env: { VUE_ENV: "server", NODE_ENV: "production" } }; 
this.global = { process: process }; 
var url = "$path";
EOT;
    $v8->executeString($js);
    $v8->executeString($renderer_source);
    $v8->executeString($app_source);
    return ob_get_clean();
  }
  public function get(Request $request) {
    $ssr = $this->render($request->path());
    return view('app', ['ssr' => $ssr]);
  }
}

AppController.php

Vue server app

The last major step is to modify the Vue server app so that we can programmatically set the URL rather than waiting for a user to do it.

The logic for doing this is inside the Promise callback function. Here’s what it does:

  • The router is set to the correct URL by pushing the global variable url
  • When the router is ready, we see if any page components are being displayed as a result of this push, telling us the route is valid. If not, we throw a 404. If so, we return the app instance.

A Promise is used because the router loads asynchronously. Once this Promise resolves, we can use the server renderer method renderVueComponentToString to SSR the instance and finally use print to return the output back to our Laravel environment.

resources/assets/js/entry-server.js

import app from './app'
import router from './router';
new Promise((resolve, reject) => {
  router.push(url);
  router.onReady(() => {
    const matchedComponents = router.getMatchedComponents();
    if (!matchedComponents.length) {
      return reject({ code: 404 });
    }
    resolve(app);
  }, reject);
})
  .then(app => {
    renderVueComponentToString(app, (err, res) => {
      print(res);
    });
  })
  .catch((err) => {
    print(err);
  });

entry-server.js

App file

The SSR logic for the multi-page app is now complete. Let’s create some router links in the page so we can test the app in a browser:

resources/asset/js/components/App.vue

<template>
  <div id="app">
    <h1>{{ title }}</h1>
    <router-view></router-view>
    <router-link :to="{ name: 'about' }">About</router-link>
    <router-link :to="{ name: 'contact' }">Contact</router-link>
  </div>
</template>
<script>
  export default {
    data() {
      return {
        title: 'Welcome To My Site'
      }
    }
  }
</script>

app.vue

Loading the home page look like this:

The real test is visiting a route in the navigation bar so the server routes handle the request and hopefully SSR the app. To do so, visit [http://localhost:9000/about](http://localhost:9000/about "http://localhost:9000/about") and inspect the source markup. As you can see, it includes the rendered app at the correct URL:

Recommended Courses:

Curso de VueJS 2

Vuejs 2 + Vuex con TypeScript Nivel PRO

Curso de Vuejs 2, Cognito y GraphQL

Learn VueJS from Scratch: The Complete 1 Hour Crash Course!

SSR con Vuejs, Vuex y Quasar Framework

#vue-js

What is GEEK

Buddha Community

Advanced Server-Side Rendering With Laravel & Vue
Luna  Mosciski

Luna Mosciski

1600583123

8 Popular Websites That Use The Vue.JS Framework

In this article, we are going to list out the most popular websites using Vue JS as their frontend framework.

Vue JS is one of those elite progressive JavaScript frameworks that has huge demand in the web development industry. Many popular websites are developed using Vue in their frontend development because of its imperative features.

This framework was created by Evan You and still it is maintained by his private team members. Vue is of course an open-source framework which is based on MVVM concept (Model-view view-Model) and used extensively in building sublime user-interfaces and also considered a prime choice for developing single-page heavy applications.

Released in February 2014, Vue JS has gained 64,828 stars on Github, making it very popular in recent times.

Evan used Angular JS on many operations while working for Google and integrated many features in Vue to cover the flaws of Angular.

“I figured, what if I could just extract the part that I really liked about Angular and build something really lightweight." - Evan You

#vuejs #vue #vue-with-laravel #vue-top-story #vue-3 #build-vue-frontend #vue-in-laravel #vue.js

Teresa  Bosco

Teresa Bosco

1598741280

Vue Laravel File Upload | Upload Image in Laravel Vue

We will use Laravel as a backend and Vue js as a frontend framework or library. In this small project, we will upload an image from the vue component. First, we download the Laravel and then install the dependencies using pm, and then we will start our project.

Steps to upload file in Laravel Vue

The first step will be to install and configure the Laravel Framework.

Step 1: Install Laravel

Go to your terminal and hit the following command.

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

After installation, go to the project folder root and type the following command.

npm install

It installs all the necessary dependencies to build Vue components.

#vue #laravel vue #vue js #laravel

Seamus  Quitzon

Seamus Quitzon

1595201363

Php how to delete multiple rows through checkbox using ajax in laravel

First thing, we will need a table and i am creating products table for this example. So run the following query to create table.

CREATE TABLE `products` (
 `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
 `name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
 `description` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
 `created_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
 `updated_at` datetime DEFAULT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci

Next, we will need to insert some dummy records in this table that will be deleted.

INSERT INTO `products` (`name`, `description`) VALUES

('Test product 1', 'Product description example1'),

('Test product 2', 'Product description example2'),

('Test product 3', 'Product description example3'),

('Test product 4', 'Product description example4'),

('Test product 5', 'Product description example5');

Now we are redy to create a model corresponding to this products table. Here we will create Product model. So let’s create a model file Product.php file under app directory and put the code below.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    protected $fillable = [
        'name','description'
    ];
}

Step 2: Create Route

Now, in this second step we will create some routes to handle the request for this example. So opeen routes/web.php file and copy the routes as given below.

routes/web.php

Route::get('product', 'ProductController@index');
Route::delete('product/{id}', ['as'=>'product.destroy','uses'=>'ProductController@destroy']);
Route::delete('delete-multiple-product', ['as'=>'product.multiple-delete','uses'=>'ProductController@deleteMultiple']);

#laravel #delete multiple rows in laravel using ajax #laravel ajax delete #laravel ajax multiple checkbox delete #laravel delete multiple rows #laravel delete records using ajax #laravel multiple checkbox delete rows #laravel multiple delete

Oleta  Orn

Oleta Orn

1593269931

How to Server Side Rendering (SSR) with Vue.js?

First of all, the purpose of the article; Why do we need an SSR approach, why and where to use SSR, what are the differences between SSR and CSR? We will consolidate what we know about these with examples.

What is Client Side Rendering (CSR)?

In client side rendering, our server returns a simple plain html page to the browser. Then, the html page returned by our server is compiled in the user’s browser with javascript and a meaningful html output is obtained. The resulting html output is compiled by the browser and presented to the user.

What is Server Side Rendering (SSR)?

In this approach, javascript is compiled on the server, not the browser. Thus, straight and meaningful html takes place directly in the browser

When Should I Consider Using SSR?

There are two main reasons for this; Better SEO and Faster time-to-content.

Performing SSR makes us stronger for SEO. Because Google Spiders (or other bots) can understand straight and meaningful html output.

Also, if we use ssr, our site open faster. Because we make the compilation on the server side so we build a more user-friendly website.

Trade-Offs

· SSR requires an environment where Node.js server can run.

· Since the compilation process is made by the server side, your costs will increase a little.

· In some cases, you will have to implement workaround solutions.

we came to the real question :)

How to Server Side Rendering (SSR) with Vue.js?

There are many methods for this. In this article I will tell you two of them. Using Nuxt.js and Using Express

#nuxt #seo #server-side-rendering #vue #ssrs