CodeIgniter4+VUEJS
Create folder project on your desktop
Create folder backend under the project folder.
Extract your downloaded ci4 source code in backend folder.
After the extraction is completed, go to the "backend" folder by typing the following command in the
terminal:
cd backend
Then type the following command in the terminal to run the project:
php spark serve
Next step: Create Database and table
Open http://localhost/phpmyadmin on your web browser and create table itc
Next, create a connection between the database and the CodeIgniter project.
Find Database.php under App\Config
Then find the following code
Apply your mysql credentials as well as your database name.
On your phpMyAdmin create table name product with this fields
'id','name', 'description', 'price', 'stock', 'image', 'variation'
Next is create your model base on your field.
Create controller named Product and put this code.
<?php
namespace App\Controllers;
use CodeIgniter\RESTful\ResourceController;
use CodeIgniter\API\ResponseTrait;
use App\Models\ProductModel;
class Product extends ResourceController
{
public function index()
{
$model = new ProductModel();
$data = $model->findAll();
if(!$data) return $this->failNotFound('No Data Found');
return $this->respond($data);
}
public function show($id = null)
{
$model = new ProductModel();
Created by: Christian I. Cabrera – College of Computer Studies
CodeIgniter4+VUEJS
$data = $model->find(['id' => $id]);
if(!$data) return $this->failNotFound('No Data Found');
return $this->respond($data[0]);
}
public function create()
{
$json = $this->request->getJSON();
$data = [
'title' => $json->title,
'price' => $json->price
];
$model = new ProductModel();
$product = $model->insert($data);
if(!$product) return $this->fail('Failed Saved', 400);
return $this->respondCreated($product);
}
public function update($id = null)
{
$json = $this->request->getJSON();
$data = [
'title' => $json->title,
'price' => $json->price
];
$model = new ProductModel();
$findById = $model->find(['id' => $id]);
if(!$findById) return $this->fail('No Data Found', 404);
$product = $model->update($id, $data);
if(!$product) return $this->fail('Update failed', 400);
return $this->respond($product);
}
public function delete($id = null)
{
$model = new ProductModel();
$findById = $model->find(['id' => $id]);
if(!$findById) return $this->fail('No Data Found', 404);
$product = $model->delete($id);
if(!$product) return $this->fail('Failed Deleted', 400);
return $this->respondDeleted('Deleted Successful');
}
}
Next step is to change your routes.php from this
$routes->get('/', 'Home::index');
To this
$routes->resource('products');
Important! You make sure to enable CORS
To enable it: navigate on your public folder and find for index.php and add this line before $app =
Config\Services::codeigniter();
<!—start here →
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Headers: X-API-KEY, Origin, X-Requested-With,
Content-Type, Accept, Access-Control-Request-Method");
Created by: Christian I. Cabrera – College of Computer Studies
CodeIgniter4+VUEJS
header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
$method = $_SERVER['REQUEST_METHOD'];
if($method == "OPTIONS") {
die();
}
install nodejs
verify if the nodejs is installed on your machine using this command
node -v
npm -v
if its installed install the vuejs cli using this command
npm install -g @vue/cli
verify vuejs if installed using this command
vue --v
Open PowerShell as Administrator: To change the Execution Policy, you'll need to open PowerShell with
administrative privileges. To do this, search for "PowerShell" in the Windows search bar, right-click on
"Windows PowerShell," and select "Run as administrator."
Check Current Execution Policy: You can check the current Execution Policy by running the following
command in the PowerShell window:
Get-ExecutionPolicy
Change Execution Policy: To change the Execution Policy to allow scripts to run, use the following
command:
Set-ExecutionPolicy RemoteSigned
This command allows scripts that you've written locally to run without a digital signature. You will be
prompted to confirm the change. Type "Y" and press Enter to confirm.
Set-ExecutionPolicy Unrestricted
Run Vue CLI: Once you've changed the Execution Policy, you should be able to run Vue CLI commands
without encountering the error. Try running your Vue CLI command again, for example:
vue -V
Create a Vue.js Project:
You can use Vue CLI to create a new Vue.js project. Navigate to the directory where you want to create
your project, then run:
vue create my-vue-app
Created by: Christian I. Cabrera – College of Computer Studies
CodeIgniter4+VUEJS
Select Manually select features
Select Babel and Router
Select 3.x
Select In Dedicated Config files
Run your project by navigating on parent directory
Created by: Christian I. Cabrera – College of Computer Studies
CodeIgniter4+VUEJS
The “backend” folder is the project we created earlier using CodeIgniter 4, while the “frontend” is the project we created using the Vue CLI.
Then, go to the “frontend” folder by typing the following command in the terminal:
cd frontend
Next, install the dependencies we need by typing the following command in the terminal:
npm install axios bootstrap@5.3.2
The above command will install axios and bootstrap
Axios makes it easier for us to interact with the API, while Bulma CSS will make it easier for us to style a user interface (UI).
To make sure our Vue JS project runs properly, type the following command in the terminal
npm run serve
Show and Delete Data (READ & DELETE)
Open the "App.vue" file in the "frontend/src" folder, then change it to the following:
<template>
<nav>
<router-link to="/">Home</router-link> |
<router-link to="/about">About</router-link>
</nav>
<router-view/>
</template>
<style>
@import '~bootstrap/dist/css/bootstrap.css'
</style>
After that, open the "main.js" file located in the "frontend/src" folder, then change it to the following:
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import axios from 'axios'
axios.defaults.baseURL="http://localhost:8080/"
createApp(App).use(router).mount('#app')
Created by: Christian I. Cabrera – College of Computer Studies
CodeIgniter4+VUEJS
Next, create a components file named “Product.vue” in the “frontend/src/components” folder.
<template>
<div>
<h1 class="title">Product List</h1>
<router-link :to="{ name: 'AddProduct' }" class="button is-primary"
>Add New</router-link>
<table class="table is-striped is-fullwidth">
<thead>
<tr>
<th>Title</th>
<th>Price</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<tr v-for="product in products" :key="product.id">
<td>{{ product.title }}</td>
<td>{{ product.price }}</td>
<td>
<router-link :to="{ name: 'EditProduct',
params: { id: product.id } }" class="button is-info is-small">Edit</router-link>
<button class="button is-danger is-small"
@click="deleteProduct(product.id)">
Delete
</button>
</td>
</tr>
</tbody>
</table>
</div>
</template>
<script>
import axios from "axios";
export default {
name: "Product",
data() {
return {
products: [],
};
},
created() {
this.getProducts();
},
methods: {
Created by: Christian I. Cabrera – College of Computer Studies
CodeIgniter4+VUEJS
async getProducts() {
try {
const response = await axios.get("product");
this.products = response.data;
} catch (error) {
console.log(error);
}
},
async deleteProduct(id) {
try {
await axios.delete(`product/${id}`);
this.getProducts();
} catch (error) {
console.log(error);
}
},
},
};
</script>
<style></style>
Then create another file named "ProductList.vue" in the "frontend/src/views" folder, then type the following code:
<template>
<Product />
</template>
<script>
import Product from "@/components/Product.vue";
export default {
name: "ProductList",
components: {
Product,
},
};
</script>
<style></style>
After that, open the “index.js” file located in the “frontend/src/router” folder, then change it to be as follows:
import { createRouter, createWebHistory } from 'vue-router'
import ProductList from '../views/ProductList.vue'
const routes = [
{
path: '/',
name: 'ProductList',
component: ProductList
}
]
const router = createRouter({
history: createWebHistory(process.env.BASE_URL),
routes
})
Created by: Christian I. Cabrera – College of Computer Studies
CodeIgniter4+VUEJS
export default router
Return to the browser, then click the “Add New” button or visit the following URL:
http://localhost:8081/
POST Data (CREATE)
Create a components file named “AddFrom.vue” in the “frontend/src/components” folder.
Then type the following code:
<template>
<div>
<h1 class="title">Add New Product</h1>
<form @submit.prevent="saveProduct">
<div class="field">
<label class="label">Title</label>
<div class="control">
<input type="text" v-model="title" class="input"
placeholder="Title/>
</div>
</div>
<div class="field">
<label class="label">Price</label>
<div class="control">
<input type="text" v-model="price" class="input"
placeholder="Price"/>
</div>
</div>
<div class="field">
<div class="control">
<button class="button is-primary">Save</button>
</div>
</div>
</form>
</div>
</template>
<script>
import axios from "axios";
export default {
name: "AddForm",
data() {
return {
title: "",
price: "",
};
},
methods: {
async saveProduct() {
try {
await axios.post("product", {
title: this.title,
price: this.price,
});
(this.title = ""), (this.price = ""), this.$router.push("/");
} catch (error) {
console.log(error);
}
Created by: Christian I. Cabrera – College of Computer Studies
CodeIgniter4+VUEJS
},
},
};
</script>
<style></style>
Then create another file named "AddProduct.vue" in the "frontend/src/views" folder, then type the following code:
<template>
<AddForm />
</template>
<script>
import AddForm from "@/components/AddForm.vue";
export default {
name: "AddProduct",
components: {
AddForm,
},
};
</script>
<style></style>
After that, open the “index.js” file located in the “frontend/src/router” folder, then change it to be as follows:
import { createRouter, createWebHistory } from 'vue-router'
import ProductList from '../views/ProductList.vue'
import AddProduct from '../views/AddProduct.vue'
const routes = [
{
path: '/',
name: 'ProductList',
component: ProductList
},
{
path: '/add',
name: 'AddProduct',
component: AddProduct
}
]
const router = createRouter({
history: createWebHistory(process.env.BASE_URL),
routes
})
export default router
Return to the browser, then click the “Add New” button or visit the following URL:
http://localhost:8081/add
UPDATE Data (UPDATE)
Create a components file named “EditFrom.vue” in the “frontend/src/components” folder.
Then type the following code:
<template>
<div>
<h1 class="title">Update Product</h1>
Created by: Christian I. Cabrera – College of Computer Studies
CodeIgniter4+VUEJS
<form @submit.prevent="updateProduct">
<div class="field">
<label class="label">Title</label>
<div class="control">
<input
type="text"
v-model="title"
class="input"
placeholder="Title"
/>
</div>
</div>
<div class="field">
<label class="label">Price</label>
<div class="control">
<input
type="text"
v-model="price"
class="input"
placeholder="Price"
/>
</div>
</div>
<div class="field">
<div class="control">
<button class="button is-primary">Update</button>
</div>
</div>
</form>
</div>
</template >
<script>
import axios from "axios";
export default {
name: "EditForm",
data() {
return {
title: "",
price: "",
};
},
created() {
this.getProductById();
},
methods: {
async getProductById() {
try {
const response = await axios.get(`product/${this.$route.params.id}`);
(this.title = response.data.title), (this.price = response.data.price);
} catch (error) {
console.log(error);
}
},
Created by: Christian I. Cabrera – College of Computer Studies
CodeIgniter4+VUEJS
async updateProduct() {
try {
await axios.put(`product/${this.$route.params.id}`, {
title: this.title,
price: this.price,
});
(this.title = ""), (this.price = ""), this.$router.push("/");
} catch (error) {
console.log(error);
}
},
},
};
</script>
<style>
</style>
Then create a view file named "EditProduct.vue" in the
"frontend/src/views" folder, then type the following code:
<template>
<EditForm />
</template>
<script>
import EditForm from "@/components/EditForm.vue";
export default {
name: "EditProduct",
components: {
EditForm,
},
};
</script>
<style>
</style>
After that, open the “index.js” file located in the “frontend/src/router” folder, then change it to be as follows:
import { createRouter, createWebHistory } from 'vue-router'
import ProductList from '../views/ProductList.vue'
import AddProduct from '../views/AddProduct.vue'
import EditProduct from '../views/EditProduct.vue'
const routes = [
{
path: '/',
name: 'ProductList',
component: ProductList
},
{
path: '/add',
name: 'AddProduct',
Created by: Christian I. Cabrera – College of Computer Studies
CodeIgniter4+VUEJS
component: AddProduct
},
{
path: '/edit/:id',
name: 'EditProduct',
component: EditProduct
},
]
const router = createRouter({
history: createWebHistory(process.env.BASE_URL),
routes
})
export default router
Created by: Christian I. Cabrera – College of Computer Studies