グッズ

Laravel と Vue.js を使用した CRUD アプリの作成

このチュートリアルでは、Laravel と Vue.js を使用してサンプル CRUD アプリのコードを記述する方法を一緒に見ていきます。

La シングルページアプリケーション DB での基本的な操作のサイクルを完了することができます: 作成、読み取り、更新、および削除 Vue.js 、Vue ルーターおよび Laravelフレームワーク .

現在、最も人気のある JS フレームワークは Angular JS と Vue JS です。 Angular JS と Vue JS は非常に使いやすく、最も人気のある JS フレームワークです。 ページを更新せずにプロジェクトまたはアプリケーション全体を管理し、強力な jquery 検証を提供します。

Vue は Laravel にあらかじめパッケージ化されています ( Laravelミックス に基づいた優れたオーサリング ツールです。 ウェブパック ) また、開発者は、トランスパイラー、コード パッケージ、ソース マップ、または最新のフロントエンド開発のその他の「汚い」側面を気にすることなく、複雑な単一ページ アプリケーションの構築を開始できます。

サーバー要件

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 次のように、index、store、update、delete メソッドにコードを追加します。

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

Defiweb.php でルートを完成させます

現在 defiそれらを終わらせる routes ファイルで web.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

app. ビュー  これは Vue アプリのメイン ファイルです。 Defi私たちは終わります ルータービュー  そのファイルで。 すべてのパスがファイルに表示されます app. ビュー  .

XNUMX月のファイル 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>

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

ここでは、コンポーネントを使用しました 読み込みが遅いvue 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 を更新する

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

APRI localhost:8000 ブラウザで。

BlogInnovazione.it

イノベーションニュースレター
イノベーションに関する最も重要なニュースをお見逃しなく。 メールで受け取るにはサインアップしてください。

最近の記事

カターニア総合病院での Apple ビューアによる拡張現実への革新的な介入

Apple Vision Pro 商用ビューアを使用した眼形成手術がカターニア総合病院で行われました。

3月2024

子供のためのぬり絵の利点 - すべての年齢層のための魔法の世界

ぬり絵を通じて細かい運動能力を発達させることで、子供たちは書くなどのより複雑なスキルを習得できるようになります。色…

2月2024

未来はここにあります: 海運業界が世界経済をどのように変革しているか

海軍部門は真の世界経済大国であり、150 億市場に向けて舵を切り続けています...

1月2024

パブリッシャーと OpenAI が人工知能によって処理される情報の流れを規制する契約に署名

先週の月曜日、フィナンシャル・タイムズ紙はOpenAIとの契約を発表した。 FT は世界クラスのジャーナリズムにライセンスを供与しています…

4月30 2024

あなたの言語でイノベーションを読む

イノベーションニュースレター
イノベーションに関する最も重要なニュースをお見逃しなく。 メールで受け取るにはサインアップしてください。

Seguici