That being said Vue or React can make building front-end easy, 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 best of both worlds.
While integrating modern JS frameworks(Vue or React) with CakePHP is really easy, there's no guide or resource which 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 tell that there's no resource which 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 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 CakePHP framework with ease. This plugin will take the all the hard work for us so that we can focus on building application with Vue.js and CakePHP.
Load plugin using below command:
bin/cake plugin load AssetMix
Generate Vue.js scaffoldings:
bin/cake asset_mix generate --dir=resources
Read about generate commands for AssetMix plugin at github.com/ishanvyas22/asset-mix#generate-c..
Install front-end dependencies:
Compile your assets:
npm run dev
Add below line in
That's it! Now we are ready to use Vue.js with CakePHP.
Once you've loaded
AssetMix helper, you now has access to
css(), etc. methods which you can use to call your compiled assets.
app.js file you've just compiled, add 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 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 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 in CakePHP application. You can file 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 comment.
- 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 find this post useful?