That being said Vue or React can make building front-end easy, but it can not replace the back-end. So it is essential to integrate both front-end and back-end properly so that we can have the best of both worlds.
While integrating modern JS frameworks(Vue or React) with CakePHP is really easy, there's no guide or resource that tells exactly how it should be done. I often see people posting questions on how or what is the best practice to integrate Vue.js with CakePHP and saying that there's no resource that can help them.
So here I am trying to answer their question on how to integrate Vue.js with CakePHP. While I'm focusing on Vue.js on front-end the general concept/idea would be the same for React or Svelte or any other front-end frameworks.
First, let's create a fresh CakePHP project via composer:
composer create-project --prefer-dist cakephp/app:~4.0 cakephp-vuejs-app
Now install AssetMix plugin:
composer require ishanvyas22/asset-mix
Why this plugin? Well, this plugin helps us integrate Laravel Mix with the CakePHP framework with ease. This plugin will take all the hard work for us so that we can focus on building the application with Vue.js and CakePHP.
Load the plugin using the below command:
bin/cake plugin load AssetMix
Generate Vue.js scaffoldings:
bin/cake asset_mix generate --dir=resources
Read about generating commands for the AssetMix plugin at github.com/ishanvyas22/asset-mix#generate-c..
Install front-end dependencies:
Compile your assets:
npm run dev
Add the below line in
That's it! Now we are ready to use Vue.js with CakePHP.
Once you've loaded
AssetMix helper, you now have access to
css(), etc. methods which you can use to call your compiled assets.
app.js file you've just compiled, add the below code into your layout
Now create a view file
templates/Pages/greet.php to call the Vue component to see it in action. Add the below code inside that file:
<div id="app"> <h1>Greetings</h1> <!-- Load AppGreet component --> <app-greet></app-greet> </div>
Now to change the text, edit
<template> <div> Welcome to CakePHP + Vue.js world! </div> </template>
npm run dev to compile the assets or you can also run
npm run watch which will watch for the changes inside the resources directory and will compile the assets automatically. Now reload the localhost:8765/pages/greet page again to see the result.
That's it! You have successfully integrated Vue.js into the CakePHP application. You can file the full source code of this post at github.com/ishanvyas22/cakephp-vuejs-skeleton.
I hope this post helps you. In case you've any questions/suggestions feel free to add comments.
CakePHP installation: book.cakephp.org/4/en/installation.html
Laravel Mix: laravel-mix.com/docs/6.0/what-is-mix
AssetMix plugin: github.com/ishanvyas22/asset-mix
Article full source code: github.com/ishanvyas22/cakephp-vuejs-skeleton
CakePHP Vue.js SPA: github.com/ishanvyas22/cakephpvue-spa
Have you found this post useful?