skip to Main Content

Problem: internal server error while passing data from vue.js to laravel using axios

I created fresh laravel project and installed breeze with vue (php artisan breeze:install vue). Then I created One menu controller and rendered menu.vue like this :

  public function index()
    {   
        $menuItems = Menu::all();
        return Inertia::render('Menu', [
            'menuItems' => $menuItems
        ]);
        
    }

Route::get('menu',[MenuController::class,'index']);
Now I created CartController

<?php

namespace AppHttpControllers;

use AppModelsCart;
use AppModelsMenu;
use IlluminateHttpRequest;


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();
    }

   
}

and here I have to store data returned from menu.vue
Menu.vue

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

The problem is when This called

axios
       .post("/cart", {
        menu_id: item.id,
         })

It gives me this error:
error

This is my app.js

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',
    },
});

This is my 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">

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

This is in storage/log file[2023-02-08 16:39:49] local.ERROR: SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'menus_id' cannot be null (SQL: insert into carts (menus_id, table, updated_at, created_at) values (?, ?, 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 carts (menus_id, table, updated_at, created_at) values (?, ?, 2023-02-08 16:39:49, 2023-02-08 16:39:49)) at D:\Trinity\7th sem\Project work\smart_QR_based_restaurant\vendor\laravel\framework\src\Illuminate\Database\Connection.php:760) [stacktrace]

2

Answers


  1. Chosen as BEST ANSWER

    I passed menu_id from post menu.vue but $cart->table gets null value so I got this error : Integrity constraint violation so for now I give this value directly

        public function store(Request $request)
    {
        $menu_id = $request->input('menu_id');
        $menu = Menu::find($menu_id);
        $cart = new Cart();
        $cart->menus_id = $menu_id;
        $cart->table = 2;
        $response = $cart->save();
    }
    

    Thank you guys for helping me 😊


  2. This might be your issue,

    you are passing this object as the post data

    {menu_id: item.id}
    

    then you call a non-existing input in your controller $request->input('id')

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

    it should be $request->input('menu_id');

    but again, check your logs to see the actual error thrown

    also, you should add a validation in your controller to make sure the ID you pass exist in your table

    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();
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search