Pass data from vue.js to laravel 9
P粉951914381
2023-08-31 16:37:26
<p>Issue: Internal server error when passing data from vue.js to laravel using axios</p>
<p>I created new laravel project and installed breece using vue (php artisan Breeze: install vue). Then I created a menu controller and rendered menu.vue like this: </p>
<pre class="brush:php;toolbar:false;">public function index()
{
$menuItems = Menu::all();
return Inertia::render('Menu', [
'menuItems' => $menuItems
]);
}</pre>
<p><code>Route::get('menu',[MenuController::class,'index']); </code>
Now I created CartController</p>
<pre class="brush:php;toolbar:false;"><?php
namespace App\Http\Controllers;
use App\Models\Cart;
use App\Models\Menu;
use Illuminate\Http\Request;
class CartController extends Controller
{
public function store(Request $request)
{
dd("CONTROLLER");
$menu_id = $request->input('id');
$menu = Menu::find($menu_id);
$cart=new Cart();
$cart->table=$request->table;
$cart->menus_id=$menu_id;
$response=$cart->save();
}
}</pre>
<p>Here I have to store the data returned from menu.vue
menu.vue</p>
<pre class="brush:php;toolbar:false;"><script setup>
import { Head } from '@inertiajs/vue3';
</script>
<template>
<Head title="Menu" />
<navbar />
<div
class="grid grid-cols-1 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-4 mx-20"
>
<div v-for="item in menuItems" :key="item.id">
<div class="p-6 bg-white rounded-lg shadow-lg">
<img
v-bind:src="'menuItemImage/' item.image"
class="w-12 h-12"
/>
<h3 class="text-lg font-medium leading-tight">
{{ item.name }}
</h3>
<button
@click="addToCart(item)"
class="mt-4 bg-blue-500 text-white py-2 px-4 rounded-lg hover:bg-blue-600"
>
Add
</button>
</div>
</div>
</div>
</template>
<script>
import navbar from "@/Layouts/NavbarLayout.vue";
import axios from "axios";
export default {
name: "Menu",
data() {
return {};
},
components: {
navbar,
},
props: ["menuItems"],
methods: {
addToCart(item) {
console.log(item.id);
axios
.post("/cart", {
menu_id: item.id,
})
.then(function (response) {
console.log(response.data);
})
.catch(function (error) {
console.log(error);
});
},
},
};
</script></pre>
<p>The problem is when this is called</p>
<pre class="brush:php;toolbar:false;">axios
.post("/cart", {
menu_id: item.id,
})</pre>
<p>It gave me this error:
Error</p>
<p>This is my app.js</p>
<pre class="brush:php;toolbar:false;">axios
import './bootstrap';
import '../css/app.css';
import { createApp, h } from 'vue';
import { createInertiaApp } from '@inertiajs/vue3';
import { resolvePageComponent } from 'laravel-vite-plugin/inertia-helpers';
import { ZiggyVue } from '../../vendor/tightenco/ziggy/dist/vue.m';
const appName = window.document.getElementsByTagName('title')[0]?.innerText || 'Laravel';
createInertiaApp({
title: (title) => `${title} - ${appName}`,
resolve: (name) => resolvePageComponent(`./Pages/${name}.vue`, import.meta.glob('./Pages/**/*.vue')),
setup({ el, App, props, plugin }) {
return createApp({ render: () => h(App, props) })
.use(plugin)
.use(ZiggyVue, Ziggy)
.mount(el);
},
progress: {
color: '#4B5563',
},
});</pre>
<p>This is my app.blade.php</p>
<pre class="brush:php;toolbar:false;"><!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title inertia>{{ config('app.name', 'Laravel') }}</title>
<!-- Fonts -->
<link rel="stylesheet" href="https://fonts.bunny.net/css2?family=Nunito:wght@400;600;700&display=swap">
<!-- Scripts -->
@routes
@vite(['resources/js/app.js', "resources/js/Pages/{$page['component']}.vue"])
@inertiaHead
</head>
<body class="font-sans antialiased">
@inertia
</body>
</html></pre>
<p>This is in storage/log file<code>[2023-02-08 16:39:49] local.ERROR: SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'menus_id' cannot be null (SQL: Insert into </code>carts<code> (</code>menus_id<code>, </code>table<code>, </code>updated_at<code>, </code> ;created_at<code>) value(?, ?, 2023-02-08 16:39:49, 2023-02-08 16:39:49)) {"Exception":"[Object] (Illuminate\\Database\ \QueryException(Code: 23000): SQLSTATE[ 23000]: Integrity constraint violation: 1048 Column 'menus_id' cannot be null (SQL: INSERT into </code>carts<code> (</code>menus_id<code>, </code>table<code>, </code >updated_at<code>, </code>created_at<code>) value(?, ?, 2023-02-08 16:39:49, 2023- 02-08 16:39:49)) in D:\Trinity\7th SEM\Project Work\smart_QR_based_restaurant\\Supplier\\laravel\\Framework\\src\\Illuminate\\Database\\ Connection.php:760) [stacktrace] </code> </p>
This may be your problem,
You are passing this object as post data
Then you call an input in the controller that does not exist
$request->input('id')
should be
$request->input('menu_id');
However, check your logs again to see the actual errors raised
Additionally, you should add validation in your controller to ensure that the ID you pass exists in the table