บทความ

การสร้างแอป CRUD ด้วย Laravel และ Vue.js

ในบทช่วยสอนนี้ เราจะดูวิธีการเขียนโค้ดของแอป CRUD ตัวอย่างด้วย Laravel และ Vue.js

La แอปพลิเคชันหน้าเดียว จะช่วยให้เราสามารถดำเนินการวงจรพื้นฐานบนฐานข้อมูล: สร้าง อ่าน อัปเดต และลบด้วย Vue.js ,วิวเราเตอร์และ กรอบ Laravel .

ปัจจุบัน JS frameworks ที่ได้รับความนิยมมากที่สุดคือ Angular JS และ Vue JS Angular JS และ Vue JS เป็นเฟรมเวิร์ก JS ที่ใช้งานง่ายและเป็นที่นิยมมากที่สุด ให้การจัดการโครงการหรือแอปพลิเคชันทั้งหมดโดยไม่ต้องรีเฟรชหน้าและการตรวจสอบ jquery ที่มีประสิทธิภาพ

Vue มาพร้อมกับ Laravel (พร้อมกับ Laravel ผสม ซึ่งเป็นเครื่องมือการเขียนที่ยอดเยี่ยมโดยอ้างอิงจาก เว็บแพ็ค ) และช่วยให้นักพัฒนาสามารถเริ่มสร้างแอปพลิเคชันหน้าเดียวที่ซับซ้อนได้โดยไม่ต้องกังวลเกี่ยวกับทรานสไพเลอร์ โค้ดแพ็กเกจ ซอร์สแมป หรือแง่มุมอื่นๆ ที่ "สกปรก" ของการพัฒนาส่วนหน้าสมัยใหม่

ข้อกำหนดของเซิร์ฟเวอร์

PHP 7.4

ลาราเวล 8.x

MySQL

ติดตั้งโครงการ Laravel

ก่อนอื่น เปิด Terminal แล้วรันคำสั่งต่อไปนี้เพื่อสร้าง laravel project ใหม่:

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

หรือหากคุณติดตั้ง Laravel Installer เป็นการพึ่งพาส่วนกลางของผู้แต่ง:

laravel new crud-spa

กำหนดค่ารายละเอียดฐานข้อมูล:

หลังการติดตั้ง ไปที่ไดเรกทอรีรากของโปรเจ็กต์ เปิดไฟล์ .env และตั้งค่ารายละเอียดฐานข้อมูลดังนี้:

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

ติดตั้งการพึ่งพา npm

เรียกใช้คำสั่งต่อไปนี้เพื่อติดตั้งการพึ่งพาส่วนหน้า:

npm install

หลังจากนั้นให้ติดตั้ง vue ,  vue-เราเตอร์  e vue-axios . Vue-axios จะถูกใช้เพื่อเรียก Laravel backend API รันคำสั่งต่อไปนี้บนเทอร์มินัล:

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

สร้างการโยกย้าย โมเดล และตัวควบคุม

สร้างเทมเพลตหมวดหมู่ การโยกย้าย และตัวควบคุม เรียกใช้คำสั่งต่อไปนี้สำหรับสิ่งนั้น:

php artisan make:model Category -mcr

-mcr  หัวข้อนี้จะสร้าง Model, Migration และ Controller โดยใช้การสังเคราะห์คำสั่งเดียว

ตอนนี้ เปิดไฟล์การย้ายหมวดหมู่จาก ฐานข้อมูล / การโยกย้าย และแทนที่โค้ดลงในฟังก์ชัน ขึ้น() :

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

ย้ายฐานข้อมูลโดยใช้คำสั่งต่อไปนี้:

php artisan migrate

ตอนนี้เปิดเทมเพลต Category.php จากapp/Models  และแก้ไขโค้ดในไฟล์ 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'];

}

?>

หลังจากนั้นให้เปิด หมวดหมู่Controller.php และเพิ่มรหัสในดัชนี จัดเก็บ ปรับปรุง และลบ วิธีการดังนี้

<?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!!'
        ]);
    }
}

Defiจบ Routes ใน web.php

Ora defiเสร็จสิ้น routes ในไฟล์ เว็บ.php e api.php . ไปที่โฟลเดอร์ routes แล้วเปิดไฟล์ web.php และ api.php แล้วอัพเดทตามนี้ routes:

routes/web.php

จดหมายข่าวนวัตกรรม
อย่าพลาดข่าวสารที่สำคัญที่สุดเกี่ยวกับนวัตกรรม ลงทะเบียนเพื่อรับพวกเขาทางอีเมล
<?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']);

สร้างแอป Vue

ในขั้นตอนนี้ ให้ไปที่ไดเร็กทอรี ทรัพยากร/มุมมองให้สร้างไฟล์ app.blade.php  และเพิ่มโค้ดต่อไปนี้เข้าไป 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>

สร้างส่วนประกอบสำหรับแอป Vue

ในขั้นตอนนี้ ให้ไปที่โฟลเดอร์ resource/jsให้สร้างโฟลเดอร์ components  และสร้างไฟล์ดังนี้:

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

แอพ.vue  เป็นไฟล์หลักของแอป Vue ของเรา Defiเราจะเสร็จสิ้น มุมมองเราเตอร์  ในไฟล์นั้น เส้นทางทั้งหมดจะปรากฏในไฟล์ แอพ.vue  .

เปิดไฟล์ Welcome.vue และอัปเดตรหัสต่อไปนี้ในไฟล์นั้น:

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

เปิดไฟล์ App.vue และอัปเดตโค้ดดังนี้:

<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>

จากนั้นเปิด resource / js / components / category / List.vue  และเพิ่มรหัสต่อไปนี้ในไฟล์:

<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>

หลังจากนั้นให้เปิด  resource /js/components/category/Add.vue  และอัปเดตรหัสต่อไปนี้ในไฟล์:

<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>

หลังจากนั้นให้เปิด  resource /js/components/category/Edit.vue  และอัปเดตรหัสต่อไปนี้ในไฟล์:


<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>

Defiเสร็จสิ้นเส้นทางไปยังแอป CRUD ใน Vue Router

ตอนนี้คุณต้อง defiจบ Vue routesและไปที่โฟลเดอร์  resource / js ให้สร้างไฟล์ route.js  และอัปเดตรหัสต่อไปนี้ในไฟล์:

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
    }
]

ที่นี่เราใช้ส่วนประกอบ โหลดช้าวิว JS จัดการการโหลดส่วนประกอบด้วยวิธี lazy ด้วยเส้นทาง ดังนั้นใน DOM คุณสามารถโหลดส่วนประกอบได้เมื่อจำเป็นผ่านเส้นทางเท่านั้น

รวมการอ้างอิง Vue.js ใน app.js

ตอนนี้คุณต้องเพิ่มพาธ vue-axios และการอ้างอิงอื่นๆ ทั้งหมด

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),
});

อัปเดต webpack.mix.js

เว็บแพ็ค.มิกซ์.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();

เรียกใช้เซิร์ฟเวอร์การพัฒนา

เปิดเทอร์มินัลแล้วรันคำสั่งนี้:

npm run watch
php artisan serve

เปิด โลคัลโฮสต์: 8000 ในเบราว์เซอร์

BlogInnovazione.it

จดหมายข่าวนวัตกรรม
อย่าพลาดข่าวสารที่สำคัญที่สุดเกี่ยวกับนวัตกรรม ลงทะเบียนเพื่อรับพวกเขาทางอีเมล

บทความล่าสุด

Veeam มีการสนับสนุนแรนซัมแวร์ที่ครอบคลุมที่สุด ตั้งแต่การป้องกันไปจนถึงการตอบสนองและการกู้คืน

Coveware by Veeam จะยังคงให้บริการตอบสนองต่อเหตุการณ์การขู่กรรโชกทางไซเบอร์ต่อไป Coveware จะนำเสนอความสามารถในการนิติเวชและการแก้ไข...

23 2024 เมษายน

การปฏิวัติสีเขียวและดิจิทัล: การบำรุงรักษาเชิงคาดการณ์กำลังเปลี่ยนแปลงอุตสาหกรรมน้ำมันและก๊าซอย่างไร

การบำรุงรักษาเชิงคาดการณ์กำลังปฏิวัติภาคส่วนน้ำมันและก๊าซ ด้วยแนวทางเชิงรุกและนวัตกรรมในการจัดการโรงงาน...

22 2024 เมษายน

หน่วยงานกำกับดูแลการต่อต้านการผูกขาดของสหราชอาณาจักรส่งสัญญาณเตือน BigTech เกี่ยวกับ GenAI

UK CMA ได้ออกคำเตือนเกี่ยวกับพฤติกรรมของ Big Tech ในตลาดปัญญาประดิษฐ์ ที่นั่น…

18 2024 เมษายน

Casa Green: การปฏิวัติพลังงานเพื่ออนาคตที่ยั่งยืนในอิตาลี

พระราชกฤษฎีกา "บ้านสีเขียว" ซึ่งกำหนดโดยสหภาพยุโรปเพื่อปรับปรุงประสิทธิภาพการใช้พลังงานของอาคารได้สรุปกระบวนการทางกฎหมายด้วย...

18 2024 เมษายน

อ่านนวัตกรรมในภาษาของคุณ

จดหมายข่าวนวัตกรรม
อย่าพลาดข่าวสารที่สำคัญที่สุดเกี่ยวกับนวัตกรรม ลงทะเบียนเพื่อรับพวกเขาทางอีเมล

ติดตามเรา