Deploy Vue SPA with Laravel Backend - laravel

I am trying to figure out how I will deploy a Vue SPA with a Laravel backend on Ubuntu on DigitalOcean
I am currently able to deploy Laravel apps on Digital Ocean with no problem at all. My new challenge is that I am creating an SPA with the Vue-Webpack template and using a standalone Laravel app as backend.
I am not sure how I will deploy this and structure my folders on Ubuntu.

one way is to keep your projects in /var/www/ side by side in two folders(laravel-api and vue-app). another way is placing your app contents inside laravel-app's resources folder. configure nginx or apache to serve the laravel api backend only.
see http://vuejs-templates.github.io/webpack/backend.html
update config/index.js
var path = require('path')
module.exports = {
build: {
index: path.resolve(__dirname, 'dist/index.html'),
assetsRoot: path.resolve(__dirname, 'dist'),
assetsSubDirectory: 'static',
assetsPublicPath: '/',
productionSourceMap: true
},
dev: {
port: 8080,
proxyTable: {}
}
}
from the docs
build.index
Must be an absolute path on your local file system.
This is where the index.html (with injected asset URLs) will be
generated.
If you are using this template with a backend-framework, you can edit
index.html accordingly and point this path to a view file rendered by
your backend app, e.g. app/views/layouts/application.html.erb for a
Rails app, or resources/views/index.blade.php for a Laravel app.
build.assetsRoot
Must be an absolute path on your local file system.
This should point to the root directory that contains all the static
assets for your app. For example, public/ for both Rails/Laravel.
What you should do is serve your main index file through Laravel routes or some other method of serving. lets say you have home.blade.php as index file
1 - show application entry point
routes.php / web.php
Route::get('/', function() {
return view('home');
});
this index file should contain the app element. then you should use vue-router for navigation which will add # after index url.
Here is how to configure javacript part
2 - Install and Import VueRouter to /resources/assets/js/bootstrap.js
3 - Use Vue router with Vue ( Vue.use(VueRouter);)
bootstrap.js
import Vue from 'vue';
import VueRouter from 'vue-router';
import axios from 'axios';
window.Vue = Vue;
Vue.use(VueRouter);
window.axios = axios;
window.axios.defaults.headers.common = {
'X-Requested-With': 'XMLHttpRequest'
};
4 - Create /resources/assets/js/routes.js file
5 - Import vue router
6 - define routes
7 - Export routes
routes.js
import VueRouter from 'vue-router';
let routes = [
{
path: '/',
component: require('./views/Home')
},
{
path: '/another',
component: require('./views/Another')
}
];
export default new VueRouter({
routes
})
8 - Create /resources/assets/js/ app.js file which would be the javascript main app
9- require the bootstrap.js and Import routes.js file we created
10 - Use it set router: router (as we are using ES6 just router as defined below would be considered as router:router)
11 - Thats the new Vue app there
app.js
require('./bootstrap');
import router from './routes';
new Vue({
el: '#app',
router
//app works go here
});
12 - Use app.js in the home.blade.php
13 - Add router links
14 - Add router view
home.blade.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>My App</title>
</head>
<body>
<div id="app">
<section class="section">
<div class="container">
<nav class="tabs is-boxed">
<div class="container">
<ul>
<router-link tag="li" to="/" exact>
<a>Home</a>
</router-link>
<router-link tag="li" to="/another">
<a>Another</a>
</router-link>
</ul>
</div>
</nav>
<router-view></router-view>
</div>
</section>
</div>
<script src="/js/app.js"></script>
</body>
</html>
15 - Remember to run webpack.
Good luck

I am assuming you have two folders for your project: client where your vue.js code goes in, and server where your backend code lives.
The short answer
Just copy the SPA build files (located in client/dist folder by default) into your server/public folder and deploy it (The same thing is true with express for Node.js).
But you can do it better
Surely you want to avoid the manual work of copying static files from client/dist to server/public on every build you do. This is easy, all you need is just changing the build folder in your client/config/index.js and make it your server/public instead of the default client/dist.
client/config/index.js:
build: {
// change "../dist" to "../../server/public" in both rules
index: path.resolve(__dirname, '../dist/index.html'),
assetsRoot: path.resolve(__dirname, '../dist'),
}
This is the recommended way to do it as described in the webpack template guide.

Check out my new project Laravue-SPA. It's a framework that pulls together Laravel, Vue.js and Vuetify to create a single page application.
It's brand new and still pre alpha release but I'll be happy to provide support and fix bugs as they're discovered!
Plus it will introduce you to the concepts needed to create an SPA even if you go off in your own direction.

Related

Displaying ziggy packeg wrong

I installed the package tightenco/ziggy, set it up as in the documentation, everything works.
But the template displays the entire list of addresses as in the screenshot
Please tell me where I went wrong
<head>
#routes
#vite('resources/js/app.js')
#inertiaHead
</head>
<body>
#inertia
</body>
<Link :href="route('listing.show', listing.id)">
<listingAddress :listing="listing" />
</Link>
app.js
import { ZiggyVue } from 'ziggy'
import { Ziggy } from './ziggy';
vite.config
.use(ZiggyVue, Ziggy)
resolve: {
alias: {
ziggy: path.resolve('/vendor/tightenco/ziggy/dist/vue.es.js')
},
},
As stated on the documentation you can exclude certain routes or include the route you want to expose to the client .
Ziggy supports filtering the routes it makes available to your JavaScript, which is great if you have certain routes that you don't want to be included and visible in the source of the response sent back to clients. Filtering routes is optional—by default, Ziggy includes all your application's named routes.
To set up basic route filtering, create a config file in your Laravel
app at config/ziggy.php and define either an only or except setting as
an array of route name patterns.
// config/ziggy.php
return [
'except' => ['_debugbar.*', '_ignition.*',],
];

add vue 3 with laravel spa as an application using IIS

I have a spa app (vue 3 + laravel 9) and I want to configure IIS in windows 10 to make it work.
I want to configure with alias using the same IP. In IIS manager from Default Web Site -> right click -> add application.
I set the Alias: myproject and physical path C:\www\myProject\public
Entering http://127.0.0.1/myproject/ the resources are not loaded ... because of the mix
<link href="{{ mix('/css/app.css') }}" rel="stylesheet">
<script src="{{ mix('/js/manifest.js') }}" defer></script>
<script src="{{ mix('/js/vendor.js') }}" defer></script>
<script src="{{ mix('/js/app.js') }}" defer></script>
it loads by default ex: http://127.0.0.1/css/app.css
I have created the entry for mix_url in config/app.php
'mix_url' => env('MIX_ASSET_URL', null)
and in .env
MIX_ASSET_URL=http://127.0.0.1/myproject
the APP_URL is the same
APP_URL=http://127.0.0.1/myproject
MIX_APP_URL=http://127.0.0.1/myproject
Webpack.js file is this:
mix.js('resources/js/app.js', 'public/js')
.extract()
.vue({ version: 3} )
.sass('resources/sass/app.scss', 'public/css')
.version();
and the for each component I load separate chunk file
path: '/login',
name: 'Login',
component: () => import(/* webpackChunkName: "login" */ '../views/auth/Login.vue')
I have build the assets again and now it loads the resources (from app.blade.php with mix) ... but it does not load the login.js ...
It complains about:
[Vue Router warn]: uncaught error during route navigation: ChunkLoadError: Loading chunk login failed......
I have tried:
changing the base url in vue-router from history: createWebHistory('/') to history: createWebHistory(process.env.MIX_APP_URL)
but the same thing.
Any idea what to be changed in order to make the changes from the base url http://127.0.0.1 to the base url http://127.0.0.1/myproject ... so all the request to be made from the new base url ?

Components are not loading with VueRouter

I have been trying to setup a simple vue application using VueRouter with Laravel. But the vue-router is not loading the components properly.
welcome.blade.php
<body>
<div id="app">
<main-app/>
</div>
<script src="{{ asset('js/app.js') }}"></script>
</body>
app.js
//import Vue from 'vue';
window.Vue = require('vue');
import VueRouter from 'vue-router';
import {
routes
} from './routes';
import MainApp from './components/MainApp.vue';
Vue.use(VueRouter);
const router = new VueRouter({
routes,
mode: 'history'
});
const app = new Vue({
el: '#app',
router,
components: {
MainApp
}
});
routes.js
import Home from './components/Home.vue'
export const routes = [{
path: '/',
component: Home,
name: 'Home'
}];
MainApp.vue
<template>
<div id="main">
<router-view></router-view>
</div>
</template>
If http://localhost:8080/vue-spa is dialed, "Home component" should be displayed (which we are displaying in Home.vue). But , nothing is displaying.
Screenshot of Dev Tools
I am new to Vue , help to find a solution for this.
Your routes.js should be -
import Home from './components/Home.vue'
export const routes = [{
path: '/vue-spa',
component: Home,
name: 'Home'
}];
Also, make sure the following is done -
You have executed the npm install command in your project. This will install the laravel-mix package, necessary for compiling your js files. (Learn more)
Then once you have your laravel-mix installed, configure the webpack.mix.js file present in your root folder. In your case (assuming the app.js file where you have written your js code is present in resources/js) the webpack.mix.js should look like -
const mix = require('laravel-mix');
mix.js('resources/js/app.js', 'public/js');
This will yield the compiled resourses/js/app.js file in public/js/app.js
Once that is done execute npm run watch. This will recompile the public/js/app.js file every time you make any changes in your resources/js/app.js code or its imported files.
Another very important step would be to set up Laravel's routes so that any request the server receives gives an entry point to your vue.js SPA. This is the probable reason that you are getting a 404 page. Define the following route in your web.php to enable that -
<?php
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::view('/{any}', 'welcome')->where('any', '.*');

Vue Router + Laravel: Reloading a page without a 404 and passing in a route varable

When reloading my single page application, I would like the url to load correctly instead of throwing a 404 error. Using Laravel 5.6, Vue.js 2.6, & MAMP.
I have tried the following code, however, I am loading different app.js files in the same welcome view based on what the URL is. Because of this structure,, this solution is not working:
Route::get('/{vue_capture?}', function () {
return view('welcome', ['app_path' => 'load different vuejs apps here in my routes/web.php file based on the url']);
})->where('vue_capture', '[\/\w\.-]*');
I would like to have refresh work with my vue router. Any suggestions, either having to do with my routes/web.php file or .htaccess file is appreciated.
Note: This .htaccess file configuration was not working for me (apache):
https://router.vuejs.org/guide/essentials/history-mode.html#example-server-configurations
//welcome blade
<div id="app">
<app></app>
</div>
<script src="{{ asset($app_path) }}"></script>
//app.vue
<div class="container-fluid px-0">
<router-view/>
</div>
Well, as far I can see, your approach was good. You are capturing all GET requests, and passing them to your Blade view.
My suggestion:
Cleaner route:
Route::get('/{any}', 'YourController#index')->where('any', '.*');
Your app.js (main JS file should look something like this):
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
import App from './views/App'
import About from './views/About'
import Home from './views/Home'
const router = new VueRouter({
mode: 'history',
routes: [
{
path: '/',
name: 'home',
component: Home
},
{
path: '/about',
name: 'about',
component: About,
},
],
});
const app = new Vue({
el: '#app',
components: { App },
router,
});
With all this configuration and your router-view, you should be fine.

laravel out of box vuejs example not working

I'm simply trying to learn vuejs with laravel and cannot get the example component working.
I have created a fresh route to simply serve the vue example for now.
create.blade.php
<!DOCTYPE html>
<html>
<head>
<title>VUE</title>
</head>
<body>
<h1>example</h1>
<div id="app">
<example></example>
</div>
<script src="/js/app.js"></script>
</body>
</html>
The app.js and example.vue files are exactly as out of the box ( so i won't bother showing example.vue here
require('./bootstrap');
window.Vue = require('vue');
Vue.component('example', require('./components/Example.vue'));
const app = new Vue({
el: '#app'
});
I have npm run watch running and it seems to have built the app files ok.
Controller and route is fine, as page is loading, but I'm getting console error as follows
app.js:1697 Uncaught TypeError: Cannot read property 'csrfToken' of
undefined
at Object.<anonymous> (app.js:1697)
at __webpack_require__ (app.js:20)
at Object.<anonymous> (app.js:778)
at __webpack_require__ (app.js:20)
at Object.<anonymous> (app.js:41430)
at __webpack_require__ (app.js:20)
at app.js:66
at app.js:69
When i click the console error in chrome it points to the line in app.js:
window.axios.defaults.headers.common['X-CSRF-TOKEN'] =
window.Laravel.csrfToken;
Is it complaining about csrftoken because I've used it as a blade template ?
How can I get it working inside laravel, just so i can play with and learn vuejs ?
The code that it is complaining about is in the resources/assets/js/bootstrap.js source, which you'll see is being referenced at the top of the app.js file. In your blade file, before you include your app.js, you can set the csrf token value.
<script>
window.Laravel.csrfToken = {{ csrf_token() }};
</script>
<script src="/js/app.js"></script>
Or, alternatively, if all you want to do is play with the example as-is, you can probably just remove that line of code from bootstrap.js. But you'll probably need it later once you start using VueJS more.
I think it's better to modify your bootstrap.js file (after axios import line) with the following:
window.axios.defaults.headers.common = {
'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
'X-Requested-With': 'XMLHttpRequest'
};

Resources