مقالات

Laravel ۽ Vue.js سان هڪ CRUD ايپ ٺاهڻ

هن سبق ۾ اسان گڏجي ڏسون ٿا ته هڪ مثال CRUD ايپ جو ڪوڊ ڪيئن لکجي، Laravel ۽ Vue.js سان.

La اڪيلو صفحو درخواست اسان کي ڊي بي تي بنيادي عملن جو هڪ چڪر مڪمل ڪرڻ جي اجازت ڏيندو: ٺاهيو، پڙهو، تازه ڪاري ۽ حذف ڪريو Vue.js , Vue Routers ۽ Laravel فريم ورڪ .

اڄڪلهه، سڀ کان وڌيڪ مشهور JS فريم ورڪ Angular JS ۽ Vue JS آهن. Angular JS ۽ Vue JS ڏاڍا صارف دوست ۽ تمام مشهور JS فريم ورڪ آهن. اهو صفحي کي ريفريش ڪرڻ ۽ طاقتور jquery جي تصديق جي بغير سڄي منصوبي يا ايپليڪيشن جو انتظام مهيا ڪري ٿو.

Vue Laravel (سان گڏ Laravel مکس , هڪ بهترين تصنيف اوزار جي بنياد تي ويب پيڪ ) ۽ ڊولپرز کي اجازت ڏئي ٿو پيچيده سنگل پيج ايپليڪيشنن کي تعمير ڪرڻ شروع ڪرڻ جي بغير ٽرانسپائلرز، ڪوڊ پيڪيجز، ماخذ نقشن يا جديد فرنٽ اينڊ ڊولپمينٽ جي ٻين "گندا" پهلوئن بابت.

سرور جي گهرج

پي پي 7.4،XNUMX

Laravel 8. ايڪس

هن MySQL

Laravel پروجيڪٽ کي انسٽال ڪريو

پهريون، ٽرمينل کوليو ۽ نئين لاراول پروجيڪٽ ٺاهڻ لاءِ هيٺ ڏنل حڪم هلائي.

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

يا، جيڪڏهن توهان Laravel انسٽالر کي موسيقار عالمي انحصار جي طور تي نصب ڪيو:

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-روٽر  e vue-axios . Vue-axios استعمال ڪيو ويندو Laravel backend API کي سڏڻ لاءِ. ٽرمينل تي ھيٺ ڏنل حڪم ھلايو:

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

لڏپلاڻ، ماڊل ۽ ڪنٽرولر ٺاهيو

ھڪڙي قسم جي ٽيمپليٽ ٺاھيو، لڏپلاڻ، ۽ ڪنٽرولر. ان لاءِ ھيٺ ڏنل حڪم ھلايو:

php artisan make:model Category -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 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'];

}

?>

ان کان پوء، کوليو 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!!'
        ]);
    }
}

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

ايپ. 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>

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

هتي اسان اجزاء استعمال ڪيو آهي سست لوڊشيڊنگوي جي ايس ھڪڙي طريقي سان اجزاء جي لوڊشيڊنگ کي منظم ڪري ٿو 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

جدت نيوز ليٽر
جدت تي سڀ کان اهم خبر نه وڃايو. انهن کي اي ميل ذريعي حاصل ڪرڻ لاء سائن اپ ڪريو.

تازيون مضمونون

Augmented Reality ۾ جديد مداخلت، ڪيٽينيا پولي ڪلينڪ ۾ ايپل ناظر سان

ڪيٽينيا پولي ڪلينڪ ۾ ايپل ويزن پرو ڪمرشل ناظر استعمال ڪندي هڪ چشمي جو آپريشن ڪيو ويو…

3 2024

ٻارن لاءِ رنگين صفحن جا فائدا - سڀني عمرن لاءِ جادوءَ جي دنيا

رنگ سازي ذريعي سٺي موٽر صلاحيتن کي ترقي ڪرڻ ٻارن کي وڌيڪ پيچيده صلاحيتن لاء تيار ڪري ٿو جهڙوڪ لکڻ. رنگ ڏيڻ…

2 2024

مستقبل هتي آهي: ڪيئن شپنگ انڊسٽري عالمي معيشت ۾ انقلاب آڻيندي آهي

بحري شعبي هڪ حقيقي عالمي معاشي طاقت آهي، جيڪا 150 بلين مارڪيٽ جي طرف نيويگيٽ ڪئي آهي ...

1 2024

پبلشرز ۽ OpenAI مصنوعي ذهانت پاران پروسيس ڪيل معلومات جي وهڪري کي منظم ڪرڻ لاءِ معاهدن تي دستخط ڪن ٿا

گذريل سومر، فنانشل ٽائمز OpenAI سان هڪ ڊيل جو اعلان ڪيو. ايف ٽي پنهنجي عالمي سطح جي صحافت کي لائسنس ڏئي ٿو ...

30 اپريل 2024

پنھنجي ٻوليءَ ۾ جدت پڙھو

جدت نيوز ليٽر
جدت تي سڀ کان اهم خبر نه وڃايو. انهن کي اي ميل ذريعي حاصل ڪرڻ لاء سائن اپ ڪريو.

اسان جي تابعداري ڪريو