Artikulo

Paggawa ng CRUD App gamit ang Laravel at Vue.js

Sa tutorial na ito, makikita natin kung paano isulat ang code ng isang halimbawang CRUD App, kasama ang Laravel at Vue.js.

La Pag-apply ng Single Page ay magbibigay-daan sa amin na kumpletuhin ang isang cycle ng mga pangunahing operasyon sa DB: gumawa, magbasa, mag-update at magtanggal gamit ang Vue.js , Vue Router at Laravel Framework .

Sa ngayon, ang pinakasikat na JS frameworks ay Angular JS at Vue JS. Angular JS at Vue JS ay napaka-user-friendly at pinakasikat na JS frameworks. Nagbibigay ito ng pamamahala ng buong proyekto o aplikasyon nang hindi nire-refresh ang pahina at malakas na pagpapatunay ng jquery.

Ang Vue ay pre-packaged kasama ang Laravel (kasama ang Laravel Mix , isang mahusay na tool sa pag-akda batay sa webpack ) at binibigyang-daan ang mga developer na magsimulang bumuo ng mga kumplikadong single page na application nang hindi nababahala tungkol sa mga transpiler, code package, source na mapa o iba pang "marumi" na aspeto ng modernong frontend development.

Mga kinakailangan sa server

PHP 7.4

Laravel 8.x

MySQL

I-install ang proyekto ng Laravel

Una, buksan ang Terminal at patakbuhin ang sumusunod na command upang lumikha ng isang bagong proyekto ng laravel:

composer create-project --prefer-dist laravel/laravel crud-spa

o, kung na-install mo ang Laravel Installer bilang composer global dependency:

laravel new crud-spa

I-configure ang mga detalye ng database:

Pagkatapos ng pag-install Pumunta sa iyong direktoryo ng ugat ng proyekto, buksan ang .env file at itakda ang mga detalye ng database bilang sumusunod:

DB_CONNECTION=mysql 
DB_HOST=127.0.0.1 
DB_PORT=3306 
DB_DATABASE=<DATABASE NAME>
DB_USERNAME=<DATABASE USERNAME>
DB_PASSWORD=<DATABASE PASSWORD>

I-install ang mga dependency ng npm

Patakbuhin ang sumusunod na command upang i-install ang mga front-end dependencies:

npm install

Pagkatapos nito, i-install tingnan ,  vue-router  e vue-axios . Gagamitin ang Vue-axios para tawagan ang Laravel backend API. Patakbuhin ang sumusunod na command sa terminal:

npm install vue vue-router vue-axios --save

Lumikha ng migration, modelo at controller

Gumawa ng template ng kategorya, paglipat, at controller. Patakbuhin ang sumusunod na utos para doon:

php artisan make:model Category -mcr

-mcr  gagawa ang paksang ito ng Model, Migration at Controller gamit ang single command synthesis.

Ngayon, buksan ang kategorya ng migration file mula sa mga database / migration at palitan ang code sa function pataas() :

public function up()
{
    Schema::create('categories', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('title');
        $table->text('description');
        $table->timestamps();
    });
}

I-migrate ang database gamit ang sumusunod na command:

php artisan migrate

Ngayon, buksan ang Category.php template mula saapp/Models  at i-edit ang code sa file model Category.php :

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Category extends Model {

   use HasFactory;

   protected $fillable = ['title','description'];

}

?>

Pagkatapos nito, buksan CategoryController.php at idagdag ang code sa index, iimbak, i-update at tanggalin ang mga pamamaraan tulad ng sumusunod:

<?php

namespace App\Http\Controllers;

use App\Models\Category;
use Illuminate\Http\Request;

class CategoryController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $categories = Category::all(['id','title','description']);
        return response()->json($categories);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $category = Category::create($request->post());
        return response()->json([
            'message'=>'Category Created Successfully!!',
            'category'=>$category
        ]);
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\Category  $category
     * @return \Illuminate\Http\Response
     */
    public function show(Category $category)
    {
        return response()->json($category);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\Category  $category
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Category $category)
    {
        $category->fill($request->post())->save();
        return response()->json([
            'message'=>'Category Updated Successfully!!',
            'category'=>$category
        ]);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\Category  $category
     * @return \Illuminate\Http\Response
     */
    public function destroy(Category $category)
    {
        $category->delete();
        return response()->json([
            'message'=>'Category Deleted Successfully!!'
        ]);
    }
}

Defitapusin ang mga Ruta sa web.php

Ora defitapusin sila routes sa mga file web.php e api.php . Pumunta sa folder routes at buksan ang web.php at api.php file at i-update ang sumusunod routes:

routes/web.php

newsletter ng pagbabago
Huwag palampasin ang pinakamahalagang balita sa pagbabago. Mag-sign up upang matanggap ang mga ito sa pamamagitan ng email.
<?php
 
Route::get('{any}', function () {
    return view('app');
})->where('any', '.*');

routes/api.php

<?php
 
Route::resource('category',App\Http\Controllers\CategoryController::class)->only(['index','store','show','update','destroy']);

Gumawa ng Vue app

Sa hakbang na ito, pumunta sa direktoryo mapagkukunan/view, lumikha ng file app.blade.php  at idagdag ang sumusunod na code sa app.blade.php:

<!doctype html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="csrf-token" value="{{ csrf_token() }}"/>
        <title>Laravel Vue CRUD App</title>
        <link href="https://fonts.googleapis.com/css?family=Nunito:200,600" rel="stylesheet" type="text/css">
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
        <link href="{{ mix('css/app.css') }}" type="text/css" rel="stylesheet"/>
    </head>
    <body>
        <div id="app">
        </div>
        <script src="{{ mix('js/app.js') }}" type="text/javascript"></script>
    </body>
</html>

Lumikha ng bahagi para sa Vue app

Sa hakbang na ito, pumunta sa folder resource/js, lumikha ng folder components  at lumikha ng mga file tulad ng sumusunod:

  • View app
  • Welcome.vue
  • Category/List.vue
  • Category/Add.vue
  • Category/Edit.vue

app. vue  ito ang pangunahing file ng aming Vue app. Defimatatapos tayo router-view  sa file na iyon. Lalabas ang lahat ng path sa file app. vue  .

Buksan ang file Welcome.vue at i-update ang sumusunod na code sa file na iyon:

<template>
    <div class="container mt-5">
        <div class="col-12 text-center">
            <h1>Laravel Vuejs CRUD</h1>
        </div>
    </div>
</template>

Buksan ang App.vue file at i-update ang code tulad ng sumusunod:

<template>
    <main>
        <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
            <div class="container-fluid">
                <router-link to="/" class="navbar-brand" href="#">Laravel Vue Crud App</router-link>
                <div class="collapse navbar-collapse">
                    <div class="navbar-nav">
                        <router-link exact-active-class="active" to="/" class="nav-item nav-link">Home</router-link>
                        <router-link exact-active-class="active" to="/category" class="nav-item nav-link">Category</router-link>
                    </div>
                </div>
            </div>
        </nav>
        <div class="container mt-5">
            <router-view></router-view>
        </div>
    </main>
</template>
 
<script>
    export default {}
</script>

Pagkatapos, buksan resource / js / components / category / List.vue  at idagdag ang sumusunod na code sa file:

<template>
    <div class="row">
        <div class="col-12 mb-2 text-end">
            <router-link :to='{name:"categoryAdd"}' class="btn btn-primary">Create</router-link>
        </div>
        <div class="col-12">
            <div class="card">
                <div class="card-header">
                    <h4>Category</h4>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-bordered">
                            <thead>
                                <tr>
                                    <th>ID</th>
                                    <th>Title</th>
                                    <th>Description</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody v-if="categories.length > 0">
                                <tr v-for="(category,key) in categories" :key="key">
                                    <td>{{ category.id }}</td>
                                    <td>{{ category.title }}</td>
                                    <td>{{ category.description }}</td>
                                    <td>
                                        <router-link :to='{name:"categoryEdit",params:{id:category.id}}' class="btn btn-success">Edit</router-link>
                                        <button type="button" @click="deleteCategory(category.id)" class="btn btn-danger">Delete</button>
                                    </td>
                                </tr>
                            </tbody>
                            <tbody v-else>
                                <tr>
                                    <td colspan="4" align="center">No Categories Found.</td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
export default {
    name:"categories",
    data(){
        return {
            categories:[]
        }
    },
    mounted(){
        this.getCategories()
    },
    methods:{
        async getCategories(){
            await this.axios.get('/api/category').then(response=>{
                this.categories = response.data
            }).catch(error=>{
                console.log(error)
                this.categories = []
            })
        },
        deleteCategory(id){
            if(confirm("Are you sure to delete this category ?")){
                this.axios.delete(`/api/category/${id}`).then(response=>{
                    this.getCategories()
                }).catch(error=>{
                    console.log(error)
                })
            }
        }
    }
}
</script>

Pagkatapos nito, buksan  resource /js/components/category/Add.vue  at i-update ang sumusunod na code sa file:

<template>
    <div class="row">
        <div class="col-12">
            <div class="card">
                <div class="card-header">
                    <h4>Add Category</h4>
                </div>
                <div class="card-body">
                    <form @submit.prevent="create">
                        <div class="row">
                            <div class="col-12 mb-2">
                                <div class="form-group">
                                    <label>Title</label>
                                    <input type="text" class="form-control" v-model="category.title">
                                </div>
                            </div>
                            <div class="col-12 mb-2">
                                <div class="form-group">
                                    <label>Description</label>
                                    <input type="text" class="form-control" v-model="category.description">
                                </div>
                            </div>
                            <div class="col-12">
                                <button type="submit" class="btn btn-primary">Save</button>
                            </div>
                        </div>                        
                    </form>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
export default {
    name:"add-category",
    data(){
        return {
            category:{
                title:"",
                description:""
            }
        }
    },
    methods:{
        async create(){
            await this.axios.post('/api/category',this.category).then(response=>{
                this.$router.push({name:"categoryList"})
            }).catch(error=>{
                console.log(error)
            })
        }
    }
}
</script>

Pagkatapos nito, buksan  resource /js/components/category/Edit.vue  at i-update ang sumusunod na code sa file:


<template>
    <div class="row">
        <div class="col-12">
            <div class="card">
                <div class="card-header">
                    <h4>Update Category</h4>
                </div>
                <div class="card-body">
                    <form @submit.prevent="update">
                        <div class="row">
                            <div class="col-12 mb-2">
                                <div class="form-group">
                                    <label>Title</label>
                                    <input type="text" class="form-control" v-model="category.title">
                                </div>
                            </div>
                            <div class="col-12 mb-2">
                                <div class="form-group">
                                    <label>Description</label>
                                    <input type="text" class="form-control" v-model="category.description">
                                </div>
                            </div>
                            <div class="col-12">
                                <button type="submit" class="btn btn-primary">Update</button>
                            </div>
                        </div>                        
                    </form>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
export default {
    name:"update-category",
    data(){
        return {
            category:{
                title:"",
                description:"",
                _method:"patch"
            }
        }
    },
    mounted(){
        this.showCategory()
    },
    methods:{
        async showCategory(){
            await this.axios.get(`/api/category/${this.$route.params.id}`).then(response=>{
                const { title, description } = response.data
                this.category.title = title
                this.category.description = description
            }).catch(error=>{
                console.log(error)
            })
        },
        async update(){
            await this.axios.post(`/api/category/${this.$route.params.id}`,this.category).then(response=>{
                this.$router.push({name:"categoryList"})
            }).catch(error=>{
                console.log(error)
            })
        }
    }
}
</script>

DefiTapusin ang landas patungo sa CRUD app sa Vue Router

Ngayon, kailangan mo defitapusin ang Vue routes, at upang gawin ito pumunta sa folder  resource / js , lumikha ng file route.js  at i-update ang sumusunod na code sa file:

const Welcome = () => import('./components/Welcome.vue' /* webpackChunkName: "resource/js/components/welcome" */)
const CategoryList = () => import('./components/category/List.vue' /* webpackChunkName: "resource/js/components/category/list" */)
const CategoryCreate = () => import('./components/category/Add.vue' /* webpackChunkName: "resource/js/components/category/add" */)
const CategoryEdit = () => import('./components/category/Edit.vue' /* webpackChunkName: "resource/js/components/category/edit" */)

export const routes = [
    {
        name: 'home',
        path: '/',
        component: Welcome
    },
    {
        name: 'categoryList',
        path: '/category',
        component: CategoryList
    },
    {
        name: 'categoryEdit',
        path: '/category/:id/edit',
        component: CategoryEdit
    },
    {
        name: 'categoryAdd',
        path: '/category/add',
        component: CategoryCreate
    }
]

Dito ginamit namin ang mga sangkap mabagal na loadingvue JS namamahala sa paglo-load ng mga bahagi sa isang paraan lazy na may mga landas, kaya sa DOM makakapag-load ka lang ng mga bahagi kapag kailangan ang mga ito sa pamamagitan ng mga landas.

Isama ang mga dependency ng Vue.js sa app.js

Ngayon ay kailangan mong idagdag ang lahat ng mga path, vue-axios at iba pang dependencies.

resource / js / app.js

require('./bootstrap');
import vue from 'vue'
window.Vue = vue;

import App from './components/App.vue';
import VueRouter from 'vue-router';
import VueAxios from 'vue-axios';
import axios from 'axios';
import {routes} from './routes';
 
Vue.use(VueRouter);
Vue.use(VueAxios, axios);
 
const router = new VueRouter({
    mode: 'history',
    routes: routes
});
 
const app = new Vue({
    el: '#app',
    router: router,
    render: h => h(App),
});

I-update ang webpack.mix.js

webpack.mix.js

const mix = require('laravel-mix');

/*
 |--------------------------------------------------------------------------
 | Mix Asset Management
 |--------------------------------------------------------------------------
 |
 | Mix provides a clean, fluent API for defining some Webpack build steps
 | for your Laravel applications. By default, we are compiling the CSS
 | file for the application as well as bundling up all the JS files.
 |
 */

mix.js('resources/js/app.js', 'public/js')
    .postCss('resources/css/app.css', 'public/css', [
        //
    ]).vue();

Patakbuhin ang development server

Buksan ang terminal at patakbuhin ang command na ito:

npm run watch
php artisan serve

Si Apri localhost:8000 sa browser.

BlogInnovazione.it

newsletter ng pagbabago
Huwag palampasin ang pinakamahalagang balita sa pagbabago. Mag-sign up upang matanggap ang mga ito sa pamamagitan ng email.

Kamakailang Mga Artikulo

Pumirma ang mga publisher at OpenAI ng mga kasunduan para i-regulate ang daloy ng impormasyong pinoproseso ng Artificial Intelligence

Noong nakaraang Lunes, inihayag ng Financial Times ang isang deal sa OpenAI. Nilisensyahan ng FT ang world-class na pamamahayag nito...

Abril 30 2024

Mga Online na Pagbabayad: Narito Kung Paano Ka Binabayaran ng Mga Serbisyo ng Streaming Magpakailanman

Milyun-milyong tao ang nagbabayad para sa mga serbisyo ng streaming, na nagbabayad ng buwanang bayad sa subscription. Karaniwang opinyon na ikaw ay…

Abril 29 2024

Itinatampok ng Veeam ang pinakakomprehensibong suporta para sa ransomware, mula sa proteksyon hanggang sa pagtugon at pagbawi

Ang Coveware ng Veeam ay patuloy na magbibigay ng mga serbisyo sa pagtugon sa insidente ng cyber extortion. Mag-aalok ang Coveware ng mga kakayahan sa forensics at remediation...

Abril 23 2024

Green and Digital Revolution: Kung Paano Binabago ng Predictive Maintenance ang Industriya ng Langis at Gas

Binabago ng predictive maintenance ang sektor ng langis at gas, na may makabago at proactive na diskarte sa pamamahala ng halaman.…

Abril 22 2024