ארטיקלען

שאַפֿן אַ CRUD אַפּ מיט Laravel און Vue.js

אין דעם טוטאָריאַל מיר זען צוזאַמען ווי צו שרייַבן די קאָד פון אַ בייַשפּיל CRUD אַפּ, מיט Laravel און Vue.js.

La איין בלאַט אַפּלאַקיישאַן וועט לאָזן אונדז צו פאַרענדיקן אַ ציקל פון יקערדיק אַפּעריישאַנז אויף דב: שאַפֿן, לייענען, דערהייַנטיקן און ויסמעקן מיט Vue.js , Vue ראָוטערס און לאַראַוועל פראַמעוואָרק .

נאָוואַדייַס, די מערסט פאָלקס JS פראַמעוואָרקס זענען Angular JS און Vue JS. Angular JS און Vue JS זענען זייער באַניצער-פרייַנדלעך און מערסט פאָלקס JS פראַמעוואָרקס. עס גיט פאַרוואַלטונג פון די גאנצע פּרויעקט אָדער אַפּלאַקיישאַן אָן רעפרעשינג די בלאַט און שטאַרק דזשקווערי וואַלאַדיישאַן.

Vue קומט פאַר-פּאַקידזשד מיט Laravel (צוזאמען מיט לאַראַוועל מיקס , אַ ויסגעצייכנט אָטערינג געצייַג באזירט אויף וועבפּאַק ) און אַלאַוז דעוועלאָפּערס צו אָנהייבן בויען קאָמפּלעקס איין בלאַט אַפּלאַקיישאַנז אָן זאָרג וועגן טראַנספּילערז, קאָד פּאַקאַדזשאַז, מקור מאַפּס אָדער אנדערע "גראָב" אַספּעקץ פון מאָדערן פראָנטענד אַנטוויקלונג.

סערווירער באדערפענישן

PHP 7.4

Laravel 8.x

מיסקל

ינסטאַלירן די Laravel פּרויעקט

ערשטער, עפענען טערמינאַל און לויפן די פאלגענדע באַפֿעל צו שאַפֿן אַ נייַע לאַראַוועל פּרויעקט:

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

אָדער, אויב איר אינסטאַלירן Laravel Installer ווי אַ קאַמפּאָוזער גלאבאלע דעפּענדענסי:

laravel new crud-spa

קאַנפיגיער דאַטאַבייס דעטאַילס:

נאָך ייַנמאָנטירונג גיין צו דיין פּרויעקט וואָרצל וועגווייַזער, עפֿענען די .ענוו טעקע און שטעלן די דאַטאַבייס דעטאַילס ווי גייט:

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-router  e vue-axios . Vue-axios וועט זיין געוויינט צו רופן די Laravel backend 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

namespace App\Models;

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

class Category extends Model {

   use HasFactory;

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

}

?>

נאָך דעם, עפענען CategoryController.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 אין טעקעס web.php e אַפּי.פפּ . גיין צו טעקע routes און עפענען די web.php און api.php טעקע און דערהייַנטיקן די פאלגענדע routes:

routes/web.php

כידעש נוזלעטער
דו זאלסט נישט פאַרפירן די מערסט וויכטיק נייַעס וועגן כידעש. צייכן אַרויף צו באַקומען זיי דורך E- בריוו.
<?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 אַפּ. Defiמיר וועלן ענדיקן ראַוטער-מיינונג  אין אַז טעקע. אַלע פּאַטס וועט דערשייַנען אין דער טעקע אַפּ  .

עפענען די טעקע 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
    }
]

דאָ מיר האָבן געניצט קאַמפּאָונאַנץ פּאַמעלעך לאָודינגvue JS מאַנידזשיז די לאָודינג פון קאַמפּאָונאַנץ אין אַ וועג lazy מיט פּאַטס, אַזוי אויף די DOM איר קענען לאָדן קאַמפּאָונאַנץ בלויז ווען זיי זענען דארף דורך פּאַטס.

אַרייַננעמען Vue.js דיפּענדאַנסיז אין app.js

איצט איר דאַרפֿן צו לייגן אַלע פּאַטס, וווע-אַקסיאָוז און אנדערע דיפּענדאַנסיז.

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

כידעש נוזלעטער
דו זאלסט נישט פאַרפירן די מערסט וויכטיק נייַעס וועגן כידעש. צייכן אַרויף צו באַקומען זיי דורך E- בריוו.

לעצטע ארטיקלען

Veeam פֿעיִקייטן די מערסט פולשטענדיק שטיצן פֿאַר ראַנסאָמוואַרע, פֿון שוץ צו ענטפער און אָפּזוך

Coveware דורך Veeam וועט פאָרזעצן צו צושטעלן ענטפער באַדינונגס פֿאַר סייבער יקסטאָרשאַן אינצידענט. קאָוועוואַרע וועט פאָרשלאָגן פאָרענסיקס און רימעדייישאַן קייפּאַבילאַטיז ...

קסנומקס אפריל קסנומקס

גרין און דיגיטאַל רעוואלוציע: ווי פּרידיקטיוו וישאַלט איז טראַנספאָרמינג די אָיל און גאַז אינדוסטריע

פּרידיקטיוו וישאַלט איז רעוואַלושאַנייזינג די ייל & גאַז סעקטאָר, מיט אַן ינאַווייטיוו און פּראָואַקטיוו צוגאַנג צו פאַבריק פאַרוואַלטונג.…

קסנומקס אפריל קסנומקס

וק אַנטיטראַסט רעגולאַטאָר רייזאַז ביגטעטש שרעק איבער GenAI

די UK CMA האט ארויס אַ ווארענונג וועגן ביג טעק ס נאַטור אין די קינסטלעך סייכל מאַרק. דאָרט…

קסנומקס אפריל קסנומקס

Casa Green: ענערגיע רעוואָלוציע פֿאַר אַ סאַסטיינאַבאַל צוקונפֿט אין איטאליע

די "קאַסע גרין" דעקרעט, פארמולירט דורך די אייראפעישע יוניאַן צו פאַרבעסערן די ענערגיע עפעקטיווקייַט פון בנינים, האט פארענדיקט זיין לעגיסלאַטיווע פּראָצעס מיט ...

קסנומקס אפריל קסנומקס

לייענען כידעש אין דיין שפּראַך

כידעש נוזלעטער
דו זאלסט נישט פאַרפירן די מערסט וויכטיק נייַעס וועגן כידעש. צייכן אַרויף צו באַקומען זיי דורך E- בריוו.

גיי אונדז