|

Laravel Vue Component Example

Laravel Vue Component Example

VueJs is the popular choice for front end when working with Laravel. In fact, Laravel ships with the boilerplate for an example Vue component that you can test out or build on for your own use. In this tutorial, we will learn how to get our front end build process set up. Laravel Mix will help in this effort, as it is a nice and convenient wrapper around the very robust webpack system – which can be at times a challenge to configure and use properly. Let’s dig into how to create our own Vue component for use in our application that will allow us to display flash messages.


How To Set Up Laravel Mix With Homestead on Windows

Now we are going to start making use of the front end build tools available in Laravel. We start by running yarn --no-bin-links in the root directory of our project.

vagrant@homestead:~/Code/forumio$ yarn --no-bin-links
yarn install v0.20.3
info No lockfile found.
[1/4] Resolving packages...
warning laravel-mix > img-loader > imagemin-gifsicle > gifsicle > bin-build > download > gulp-decompress > gulp-util@3.0.8: gulp-util is deprecated - replace it, following the guidelines at https://medium.com/gulpjs/gulp-util-ca3b1f9f9ac5
[2/4] Fetching packages...
warning fsevents@1.1.3: The platform "linux" is incompatible with this module.
info "fsevents@1.1.3" is an optional dependency and failed compatibility check. Excluding it from installation.
[3/4] Linking dependencies...
[4/4] Building fresh packages...
success Saved lockfile.
warning Your current version of Yarn is out of date. The latest version is "1.3.2" while you're on "0.20.3".
info To upgrade, run the following command:
$ npm upgrade --global yarn
Done in 164.97s. 

It looks like yarn is pretty out of date here, so we do an upgrade using these commands.

curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | sudo apt-key add -
echo "deb https://dl.yarnpkg.com/debian/ stable main" | sudo tee /etc/apt/sources.list.d/yarn.list

Now we do an install one more time to be sure everything is good

vagrant@homestead:~/Code/forumio$ yarn install --no-bin-links
yarn install v1.3.2
[1/4] Resolving packages...
[2/4] Fetching packages...
info fsevents@1.1.3: The platform "linux" is incompatible with this module.
info "fsevents@1.1.3" is an optional dependency and failed compatibility check. Excluding it from installation.
[3/4] Linking dependencies...
[4/4] Building fresh packages...
Done in 45.24s.

Ok the install looks good, now we try to run yarn run dev and get a few troubles.

vagrant@homestead:~/Code/forumio$ yarn run dev
yarn run v1.3.2
$ npm run development

> @ development /home/vagrant/Code/forumio
> cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js

sh: 1: cross-env: not found

npm ERR! Linux 4.4.0-51-generic
npm ERR! argv "/usr/bin/nodejs" "/usr/bin/npm" "run" "development"
npm ERR! node v6.10.0
npm ERR! npm  v3.10.10
npm ERR! file sh
npm ERR! code ELIFECYCLE
npm ERR! errno ENOENT
npm ERR! syscall spawn
npm ERR! @ development: cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js
npm ERR! spawn ENOENT
npm ERR!
npm ERR! Failed at the @ development script 'cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js'.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the  package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js
npm ERR! You can get information on how to open an issue for this project with:
npm ERR!     npm bugs
npm ERR! Or if that isn't available, you can get their info via:
npm ERR!     npm owner ls
npm ERR! There is likely additional logging output above.

npm ERR! Please include the following file with any support request:
npm ERR!     /home/vagrant/Code/forumio/npm-debug.log
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

Ok, turns out we can fix this by updating the package.json like so:

Now we run yarn run dev one more time, and it looks like we are cooking.

yarn run v1.3.2
$ node node_modules/cross-env/dist/bin/cross-env.js NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js
 95% emitting

 DONE  Compiled successfully in 9455ms                                                                                       3:43:03 PM
                                                                                                                                                                                                                              Asset     Size  Chunks                    Chunk Names
  fonts/vendor/bootstrap-sass/bootstrap/glyphicons-halflings-regular.eot?f4769f9bdb7466be65088239c12046d1  20.1 kB          [emitted]  
fonts/vendor/bootstrap-sass/bootstrap/glyphicons-halflings-regular.woff2?448c34a56d699c29117adc64c43affeb    18 kB          [emitted]  
 fonts/vendor/bootstrap-sass/bootstrap/glyphicons-halflings-regular.woff?fa2772327f55d8198301fdb8bcfc8158  23.4 kB          [emitted]  
  fonts/vendor/bootstrap-sass/bootstrap/glyphicons-halflings-regular.ttf?e18bbf611f2a2e43afc071aa2f4e1512  45.4 kB          [emitted]  
  fonts/vendor/bootstrap-sass/bootstrap/glyphicons-halflings-regular.svg?89889688147bd7575d6327160d64e760   109 kB          [emitted]  
                                                                                               /js/app.js  1.23 MB       0  [emitted]  [big]  /js/app
                                                                                             /css/app.css   147 kB       0  [emitted]         /js/app
Done in 15.59s.


Vue Components In Laravel

Laravel has an example component set up for you in the base install. There are two files to look at to understand how these work. Those are ExampleComponent.vue located in resources/assets/js/components and app.js located in resources/assets/js.
vue component in laravel

Here is what is contained in each file to start.

ExampleComponent.vue

app.js

With these two files in place and after running yarn run dev like we did already, we could actually render this component in the browser by adding it’s markup into the app.blade.php layout file like so:

vue component in the browser


Making Your Own Vue Component

We now understand how the mechanics work of putting together a Vue component in Laravel. Our goal here is to create a flash message component that we can use in our application. Our markup in the blade file would look at bit like this:

Let’s just rename ExampleComponent.vue to Flash.vue and let PHPStorm do the refactor for us.
creating a flash message component in vue

We’ll also need to manually rename the component to flash.
naming the vue component in javascript

Additionally, we will update the HTML and JavaScript in the Vue Component itself to reflect an alert.


Building Your Source Files

Because we are now working in the realm of a build tool on the front end, when updates are made to the “source” files so to speak, they will not get updated in the browser. You need to manually build the files again using either npm run dev or yarn run dev. Once we complete the update, we can once again view our new flash component in the browser.
rendered vue flash component


Turning On File Watching in Mix/Webpack

Like me, you may be feeling like it’s a bit of a pain to be required to visit the terminal after any changes you make to your files, and then run the command to rebuild everything. For this, you can turn on file watching via npm run watch or npm run watch-poll. Now when you make file edits, you can watch the recomplilation of the files happening automatically in the terminal like we see here.
laravel watch hot reload working on windows


Accepting Properties Using Props

In order to make our flash message dynamic and not use the same canned message each time, we need to be able to pass it some variable data. This is accomplished by way of props in VueJs. Here we will update our Vue component to use a prop. Essentially what is happening now is, the Vue instance is going to look on the HTML markup in the view file of the custom component. So for us, this is the <flash> tag. It is going to look on that tag for a property named message. Whatever the value is on that message property, is the value that gets used in the prop. Makes sense?


Adding Styling In The Vue Component

The Vue component itself has three sections. These would be the <template>, the <script>, and the <style> sections. How about we add some basic styling to our component so it just gives us a nice little message rather than taking up so much space. Here is our updated Flash.vue file.

Now by using the simple markup of

in the blade file, we’ll get a nice result like we see here.
css in the vue component

You can also look in Developer Tools to see your component in action!
inspect vue instance in vue developer tools


Inspecting PHP Session Data To Populate The Vue Component

Whenever flash session data is created in our application, it is happening in Laravel or PHP. We need to somehow tap into those messages, so that they can be used in JavaScript or Vue. We’ll do this by populating the message property like so:

Now, when flash data gets populated in Laravel, the message property value on the <flash> component will get populated, and Vue will render a nice flash message for us with a custom message.


Controlling Visibility with v-show

There will not always be a populated flash session to read a message from. In those cases, we don’t really want to display the flash markup in the browser. This can be accomplished by using the v-show directive in Vue. Here we add a v-show directive and the accompanying property in the Vue script code. If the show property is false, the template is not rendered in the browser. If the show property is true however, it is displayed in the browser.
v-show vue diagram


Using the created() method in Vue

Now we need a way to dynamically update the value of the show property. We can accomplish this with the created() method.

Let’s see how we can implement this in our code.


Populating The Flash Session

Now, all that is left to do really is to populate the flash session variable when something happens in our application that we want to notify the user about. How about when a new thread is created? For this, we can make a simple call to the with() method on the store() method of the ThreadsController.

Add a new thread.
populate flash session display flash message

The user is redirected to the thread, and sees the flash message.
vue flash message working


Making A Flash Message Disappear After X Amount of Time

With the implementation so far, that flash message will stay on the screen until the user refreshes the page or visits a different page. Of course by using JavaScript, we can automatically make the flash message disappear after a certain period of time. We can do this right in the Vue script of the template. We’ll do this by adding two methods to the methods object of the Vue component. The flash() method will cause the message to appear, and the hide() method will cause it to disappear after 4 seconds. The syntax uses ES6 so you may want to check out our es6 arrow functions tutorial as well as our es6 class tutorial. Once you understand those concepts, the full Vue component markup here should make good sense.

You’ll also need to add this JavaScript code to the bootstrap.js file of your project in order for this component to work.

With all of the legwork we have done now, adding a flash message to virtually anything you like in your Laravel application should be super easy. Right now we added a flash message to when a new thread is created, but it could easily be added to when a new reply to a thread is added, when a thread is favorited, when a user logs in or out, or whatever else you like.


Laravel Vue Component Example Summary

This was a fun tutorial that took a dive into getting set up for front end build processes which focus on configuring your own Vue components that can be used in your blade files. Getting the build tools set up can be just slightly challenging, and if you run into errors like you saw in this tutorial, there are many fixes you can find online which mostly fix those stubborn cross platform issues when running a virtual machine. We made it though, and everything is working fantastic so great work!