Dengan JSON API kita dapat mengambil data sesuai dengan kebutuhan, dalam catatan kali ini membuat data produk pada Laravel kemudian menampilkan datanya pada vuejs melalui API. disini akan membuat panggilan ke laravel melalui permintaan GET sederhana.
Bagaimana Melakukannya ikuti catatan berikut ini.
Pertama kita buat dulu CRUD data produk pada laravel. yang dapat membuat data produk ini hanyalah admin jadi kita harus membuat login terlebih dahulu untuk admin. ketik perintah berikut ini.
1 |
php artisan make:auth |
kemudian buat ProductController
1 |
php artisan make:controller Admin\ProductController --resource |
dan masukan kode sebagai berikut
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 |
<?php namespace App\Http\Controllers\Admin; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use App\Product; use Auth, Session, Redirect; class ProductController extends Controller { public function index() { $product = Product::all(); return view('admin.product.index', compact('product')); } public function create() { return view('admin.product.create'); } public function store(Request $request) { $product = new Product; $product->name = $request->name; $product->description = $request->description; $product->price = $request->price; $product->stock = $request->stock; $product->save(); Session::flash('message', 'Product telah tersimpan'); return Redirect::to('admin/product'); } public function show($id) { // } public function edit($id) { $product = Product::find($id); return view('admin.product.edit', compact('product')); } public function update(Request $request, $id) { $product = Product::find($id); $product->name = $request->name; $product->description = $request->description; $product->price = $request->price; $product->stock = $request->stock; $product->save(); Session::flash('message', 'Mengganti Product sukses!'); return Redirect::to('admin/product'); } public function destroy($id) { $product = Product::find($id); $product->delete(); Session::flash('message', 'Product telah dihapus'); return Redirect::to('admin/product'); } } |
buat struktur data product
1 |
php artisan make:model Product -m |
dan strukturnya adalah sebagai berikut
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateProductsTable extends Migration { public function up() { Schema::create('products', function (Blueprint $table) { $table->increments('id'); $table->string('name'); $table->text('description'); $table->decimal('price', 15, 2)->default(0); $table->integer('stock'); $table->timestamps(); }); } public function down() { Schema::dropIfExists('products'); } } |
kemudian pada folder Api buat pula ProductController
1 |
php artisan make:controller Api\ProductController |
yang kodenya adalah sebagai berikut
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<?php namespace App\Http\Controllers\Api; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use App\Product; class ProductController extends Controller { public function getProducts() { $products = Product::where('stock', '<>', 0)->get(); return response()->json(['products' => $products], 200); } } |
dan pada router
masukan kode sebagai berikut
1 2 3 4 5 6 7 8 9 10 11 12 |
<?php use Illuminate\Http\Request; Route::middleware('auth:api')->get('/user', function (Request $request) { return $request->user(); }); |
Kemudian pada VueJS Project buat file Welcome.vue dan kodenya sebagai berikut
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
<template> <div class="px-3 py-3 pt-md-5 pb-md-4 mx-auto"> <div class="row"> <div v-for="product in products" :key="product.id" class="col-md-4"> <div class="card mb-4 shadow-sm"> <img class="card-img-top" src="https://www.gstatic.com/webp/gallery/4.jpg" alt="Card image cap"> <div class="card-body"> <h5 class="card-title">{{product.name}}</h5> <p class="card-text">Rp. {{product.price}}</p> <div class="d-flex justify-content-between align-items-center"> <div class="btn-group"> <button type="button" class="btn btn-sm btn-outline-secondary">View</button> <button type="button" class="btn btn-sm btn-outline-secondary">Buy</button> </div> <small class="text-muted">Stock: {{product.stock}}</small> </div> </div> </div> </div> </div> </div> </template> <script> export default { name: 'Welcome', created () { this.$store.dispatch('products') }, computed: { products () { return this.$store.getters.products } } } </script> |
dan pada store adalah sebagai berikut
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 |
import Vue from 'vue' import Vuex from 'vuex' import axios from 'axios' Vue.use(Vuex) axios.defaults.baseURL = 'http://mylaravel.test/api' export const store = new Vuex.Store({ state: { token: localStorage.getItem('access_token') || null, products: [] }, mutations: { setToken(state, token) { state.token = token }, destroyToken(state) { state.token = null }, setProducts (state, products) { state.products = products } }, actions: { register(context, data) { return new Promise((resolve, reject) => { axios.post('/register', { name: data.name, email: data.email, password: data.password }) .then(response => { resolve(response) }) .catch(error => { reject(error) }) }) }, login(context, payload) { return new Promise((resolve, reject) => { axios.post('/login', { username: payload.username, password: payload.password, }) .then(response => { const token = response.data.access_token console.log(response.data) localStorage.setItem('access_token', token) context.commit('setToken', token) resolve(response) }) .catch(error => { console.log(error) reject(error) }) }) }, logout(context) { axios.defaults.headers.common['Authorization'] = 'Bearer ' + context.state.token if (context.getters.loggedIn) { return new Promise((resolve, reject) => { axios.post('/logout') .then(response => { localStorage.removeItem('access_token') context.commit('destroyToken') resolve(response) }) .catch(error => { localStorage.removeItem('access_token') context.commit('destroyToken') reject(error) }) }) } }, products(context) { axios.get('/products/get') .then(response => { context.commit('setProducts', response.data) console.log(response.data) }) .catch(error => { console.log(error) }) } }, getters: { products(state) { return state.products.products }, } }) |
dan pada router sebagai berikut 😀
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
import Welcome from '@/components/Welcome' import Signin from '@/components/auth/Signin' import Signup from '@/components/auth/Signup' import Signout from '@/components/auth/Signout' const routes = [ { path: '/', name: 'Welcome', component: Welcome, }, { path: '/signin', name: 'Signin', component: Signin, props: true, }, { path: '/signup', name: 'Signup', component: Signup, }, { path: '/signout', name: 'Sigout', component: Signout, }, ] export default routes |