將資料從 vue.js 傳遞到 laravel 9
P粉951914381
P粉951914381 2023-08-31 16:37:26
0
1
556
<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< ;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>table<code>, </code >updated_at<code>, </code>created_at</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粉951914381
P粉951914381

全部回覆(1)
P粉373596828

這可能是你的問題,

您正在將此物件作為發布資料傳遞

{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();
}
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板