Laravel 8 with Vue 3
Prerequisite
- Laravel >=8
- Laravel Mix >=6
- Node version >=12.14
Creating Laravel Project: First Create a Laravel project using below command
composer create-project laravel/laravel Laravel_Vue_Ex
Creating Database: Create a new database in mysql with the name Laravel vue. Then Open ‘env’ file and change Database configuration
DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=laravel_vue
Table Creation: Now we will create a product table.
php artisan make:model Product -m
Relationship: One User will add one to many products. And one product belongs to only one user.
This below command will create one model class named “Product”, one migration class named “CreateProductsTable”.
Migration: From database->migrations-> Open the CreateProductsTable table add ‘name’ and ‘details’ column.
public function up(){ Schema::create('products', function (Blueprint $table) { $table->id(); $table->string('name'); $table->text('details'); $table->timestamps(); }); }
But the table products still not added because we have to run below command
php artisan migrate
Migrating: 2022_02_15_060026_create_products_table Migrated: 2022_02_15_060026_create_products_table (75.60ms)
HasMany: In User model add below function
public function products(){ return $this->hasMany(Product::class); }
BelongsTo: Product model belongs to User Model
public function users(){ return $this->belongsTo(User::class); }
Controller: Let’s create a controller
php artisan make:controller ProductController
Then in routes/api.php add below code.
Route::middleware('api')->group(function (){ Route::resource('products',ProductController::class); });
Resource: What resource do is it give some route atomically so we do not have to create them.
We can check the route list
php artisan route:list
Learn about middleware
Adding Vue 3 to Laravel:
npm install --save vue@next && npm install --save-dev vue-loader@next
In Webpack.mix.js
Add vue()
mix.js('resources/js/app.js', 'public/js') .vue() .postCss('resources/css/app.css', 'public/css', [ // ]);
Now we will create view components and add them on Laravel blade template.
Create a folder name ‘components’ in resource->js-> components’
Add a vue file with the name of “Create_View.vue” and add below code
<template>
<form @submit.prevent=”add_products”>
<!-- username input --> <input type="text" v-model="username"> <!-- email input --> <input type="text" v-model="details" > <!-- submit button --> <button type="submit">Submit</button> </form> </template> <script> export default { data() { return { username: '', details: '', } }, methods: { // submit the form to our backend api async add_products() { const res = await fetch('/api/products', { method: 'POST', headers: { 'Content-Type': 'application/json' }, // pass in the information from our form body: JSON.stringify({ username: this.username, details: this.details, }) }).then(response=>{ console.log(response) }) } } } </script>
If we check the route:list we will see few Route and Method like below
Method:POST Route:api/products Controller Method:products.store Action: App\Http\Controllers\ProductController@store
We have to add store method to ProductController
public function store(Request $request) { $test = json_decode($request->getContent(), true); $username = $test['username']; $detail = $test['details']; $product = new Product([ 'name' => $username, 'details' => $detail ]); $product->save(); return response()->json('Product created!'); }
Now in app.js we have to add this component with vue.
First, we have to import Vue
import {createApp} from 'vue'
Then import the component from directory that we have created earlier
import Create_Product from "./componets/Create_Product";
Then we will create an object of CreateApp
const app =createApp({});
then we can add the component to vue
app.component('create-pro',Create_Pro);
Then we will add the vue to DOM
app.mount('#app')
Then in our Blade view we can use “create-pro”
<create-pro/>
We will have to app app.js in our blade
<script src="{{ asset('js/app.js') }}"></script>
Then run
npm run watch
This command will continue to watch css,js and recompile webpack if anything changes.
Now run the application
Once we submit the form, we have to inspect the page. And in console we will see below status.
Response {type: 'basic', url: 'http://127.0.0.1:8000/api/products', redirected: false, status: 200, ok: true, …}
Also in database data updated as well.
Learn more about Mix
https://laravel.com/docs/8.x/mix