DEV Community

Cover image for Send variable straight to front-end without request with Laravel and Vue.js
Tiago A.
Tiago A.

Posted on

Send variable straight to front-end without request with Laravel and Vue.js

  • Q: What is it for?
  • A: A static front-end app using variables from PHP

Intro

I’ve done this in a front-end app that should be customized, based on the server it was hosted. It was just one front app hosted in many servers with an unique addresses.

To get this working, the front-end app should be compiled and served by Laravel.
We accomplish that by putting the front-end compiled files in the Laravel’s /public dir.

Making it happen

Initialize a default app with @vue/cli:

vue create front

Create a Laravel app with Composer:

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

To make Laravel serve the front-end app we have to modify the main route in /routes/web.php:

Route::get('/{any}', function () {
 return view('vue', [
 'color' => $_SERVER['SERVER_PORT'] == 8000 ? 'red' : 'blue'
 ]);
})->where(['any' => '.*']);

The where condition makes the custom routes in the front.
It will be necessary to add the public dir in Laravel’s views config in /config/view.php:
Add the var $color in front-end’s /public/index.html:

<style>
    body {
        background-color: {{ $color }};
    }
</style>

*Note the Blade syntax, it won’t work in Vue dev environment.
Build the front-end app with:

npm run build

After build transfer all of the content /dist dir to Laravel’s /public and rename the file index.html to vue.blade.php.
To check the final result, start the Laravel app in two diferent ports:

php artisan serve --port 8000
php artisan serve --port 9000

You should see:
Preview

This is just a simple example of how to pass a var from Laravel to Vue.js. In this case it was just a string defined in Laravel that was printed in CSS.
Have I helped you? Let me know:

Top comments (0)