首页  >  问答  >  正文

将数据从 vue.js 传递到 laravel 9

<p>问题:使用 axios 将数据从 vue.js 传递到 laravel 时出现内部服务器错误</p> <p>我创建了新的laravel项目并使用vue安装了breece(php artisan Breeze:安装vue)。然后我创建了一个菜单控制器并渲染了 menu.vue,如下所示:</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> 现在我创建了 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>这里我必须存储从menu.vue返回的数据 菜单.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>问题是当这被调用时</p> <pre class="brush:php;toolbar:false;">axios .post("/cart", { menu_id: item.id, })</pre> <p>它给了我这个错误: 错误</p> <p>这是我的 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>这是我的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>这是在存储/日志文件中<code>[2023-02-08 16:39:49] local.ERROR:SQLSTATE [23000]:完整性约束违规:1048 列'menus_id'不能为空(SQL:插入放入 </code>carts<code> (</code>menus_id<code>, </code>table<code>, </code>updated_at<code>, </code>created_at<code>) 值 (?, ?, 2023-02-08 16:39:49, 2023-02-08 16:39:49)) {"异常":"[对象] (Illuminate\\Database\\QueryException(代码: 23000): SQLSTATE[ 23000]:完整性约束违规:1048 列 'menus_id' 不能为空(SQL:插入 </code>carts<code> (</code>menus_id<code>, </code>table<code>, </code >updated_at<code>, </code>created_at<code>) 值 (?, ?, 2023-02-08 16:39:49, 2023-02-08 16:39:49)) 在 D:\\Trinity \\第七届SEM\\项目工作\\ smart_QR_based_restaurant \\供应商\\ laravel \\框架\\ src \\ Illuminate \\ Database \\ Connection.php:760)[stacktrace] </ code> </ p>
P粉951914381P粉951914381438 天前530

全部回复(1)我来回复

  • P粉373596828

    P粉3735968282023-09-01 11:50:25

    这可能是你的问题,

    您正在将此对象作为发布数据传递

    {menu_id: item.id}

    然后你在控制器中调用一个不存在的输入$request->input('id')

    $menu_id = $request->input('id');
    $menu = Menu::find($menu_id);

    应该是$request->input('menu_id');

    但是,再次检查您的日志以查看引发的实际错误

    此外,您应该在控制器中添加验证,以确保您传递的 ID 存在于表中

    public function store(Request $request) {
        
        $request->validate([
            'menu_id' => 'required|exists:menus,id'
        ]);
        
        
        $menu_id = $request->input('menu_id');
        $menu = Menu::find($menu_id);
        $cart=new Cart();
        $cart->table=$request->table;
        $cart->menus_id=$menu_id;
        $response=$cart->save();
    }

    回复
    0
  • 取消回复