用品

使用 Laravel 和 Vue.js 創建一個 CRUD 應用程序

在本教程中,我們一起了解如何使用 Laravel 和 Vue.js 編寫示例 CRUD 應用程序的代碼。

La 單頁申請 將允許我們完成對數據庫的基本操作循環:創建、讀取、更新和刪除 Vue.js , Vue 路由器和 Laravel框架 .

現在最流行的 JS 框架是 Angular JS 和 Vue JS。 Angular JS 和 Vue JS 是非常用戶友好且最受歡迎的 JS 框架。 它提供了對整個項目或應用程序的管理,無需刷新頁面和強大的 jquery 驗證。

Vue 預先打包在 Laravel 中(連同 Laravel 混合 ,一個優秀的創作工具,基於 的WebPack ) 並允許開發人員開始構建複雜的單頁應用程序,而無需擔心轉譯器、代碼包、源映射或現代前端開發的其他“骯髒”方面。

服務器要求

Php 7.4

拉維爾 8.x

MySQL的

安裝 Laravel 項目

首先,打開終端並運行以下命令來創建一個新的 laravel 項目:

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

或者,如果您將 Laravel Installer 安裝為 composer 全局依賴項:

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 後端 API。 在終端上運行以下命令:

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

創建遷移、模型和控制器

創建類別模板、遷移和控制器。 為此運行以下命令:

php artisan make:model Category -mcr

-mcr  本主題將使用單一命令合成創建模型、遷移和控制器。

現在,打開類別遷移文件 數據庫/遷移 並將代碼替換為函數 向上() :

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 類別.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'];

}

?>

之後,打開 類別控制器.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完成 web.php 中的路由

現在 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 應用程序

這一步,進入目錄 資源/視圖, 創建文件 應用程序刀片.php  並將以下代碼添加到 應用程序刀片.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

app.vue  它是我們 Vue 應用程序的主文件。 Defi我們會完成 路由器視圖  在那個文件中。 所有路徑都會出現在文件中 app.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完成Vue Router中CRUD應用程序的路徑

現在,你必須 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
    }
]

這裡我們使用了組件 加載緩慢VueJS 以某種方式管理組件的加載 lazy 帶有路徑,因此在 DOM 上您可以僅在需要時通過路徑加載組件。

在 app.js 中包含 Vue.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

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();

運行開發服務器

打開終端並運行此命令:

npm run watch
php artisan serve

四月 本地主機:8000 在瀏覽器中。

BlogInnovazione.it

創新通訊
不要錯過有關創新的最重要新聞。 註冊以通過電子郵件接收它們。

最近的文章

英國反壟斷監管機構對 GenAI 向 BigTech 發出警報

英國 CMA 對大型科技公司在人工智慧市場的行為發出了警告。那裡…

18月2024

Casa Green:義大利永續未來的能源革命

歐盟為提高建築物能源效率而製定的「綠色案例」法令已結束立法程序…

18月2024

根據新的 Casaleggio Associati 報告,義大利電子商務成長了 27%

Casaleggio Associati 發布了義大利電子商務年度報告。題為「人工智慧商務:人工智慧電子商務的前沿」的報告...

17月2024

絕妙點子:Bandalux 推出 Airpure®,淨化空氣的窗簾

不斷技術創新以及對環境和人民福祉的承諾的結果。 Bandalux 推出 Airpure®,一款帳篷…

12月2024