Nameless_0's avatar

Laravel 5 vuejs SQLSTATE[23000]: Integrity constraint violation

Hello everybody. I am trying to create a crud app but when I try to add I get the error

POST http://itventors.test/api/employee 500 (Internal Server Error)

and SQL state error

Illuminate\Database\QueryException: SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'employee_id' cannot be null (SQL: insert into `employees` (`id`, `employee_id`, `last_name`, `first_name`, `middle_name`, `email`, `updated_at`, `created_at`) values (, , , , , , 2018-06-29 08:13:14, 2018-06-29 08:13:14)) in file C:\xampp\htdocs\itventors\vendor\laravel\framework\src\Illuminate\Database\Connection.php on line 664
Stack trace:

Here is the code:

can someone check the add function? Thanks

<template>
 <div>
    <h2><center>Employee's Info</center></h2>
    <form @submit.prevent="addEmployee" class="mb-3">
        <div class="form-group">
            <input type="text" class="form-control" placeholder="Employee No" v-model="employee.employee_no">
        </div>
        <div class="form-group">
            <input type="text" class="form-control" placeholder="Last name" v-model="employee.last_name">
        </div>
        <div class="form-group">
            <input type="text" class="form-control" placeholder="First name" v-model="employee.first_name">
        </div>
        <div class="form-group">
            <input type="text" class="form-control" placeholder="Middle name" v-model="employee.middle_name">
        </div>
        <div class="form-group">
            <input type="text" class="form-control" placeholder="Email" v-model="employee.email">
        </div>
            <button type="submit" class="btn btn-light btn-block">Save</button>
        </form>
        <nav aria-label="Page navigation example">
        <ul class="pagination">
               <li  v-bind:class="[{disabled: !pagination.prev_page_url}]" class="page-item"><a class="page-link" href="#" @click="fetchEmployees(pagination.prev_page_url)">Previous</a></li>

                <li class="page-item disabled"><a class="page-link text-dark" href="#">Page {{ pagination.current_page }} of {{ pagination.last_page }}</a></li>

               <li v-bind:class="[{disabled: !pagination.next_page_url}]" class="page-item"><a class="page-link" href="#" @click="fetchEmployees(pagination.next_page_url)">Next</a></li>
              </ul>
        </nav>
        <div class="card card-body mb-2" v-for="employee in employees" v-bind:key="employee.id">
            <h4>{{ employee.last_name }}, {{ employee.first_name }} {{ employee.middle_name }}</h4>
            <p>{{ employee.email }}</p>
            <hr>
            <button @click="deleteEmployee(employee.id)" class="btn btn-danger">Delete</button>
        </div>
    </div>
</template>

<script>
    export default {
        data() {
            return {
            employees: [],
            employee: {
                id: '',
                employee_no: '',
                last_name : '',
                first_name : '',
                middle_name : '',
                email: ''
            }, 
                employee_id: '',
                pagination: {},
                edit: false
            }
        },

        created(){
            this.fetchEmployees();
        },

        methods: {
            fetchEmployees(page_url) {
                let vm =  this;
                page_url =  page_url || '/api/employees';
                fetch(page_url)
                    .then(res => res.json())
                    .then(res => {
                        this.employees = res.data;
                        vm.makePagination(res.meta, res.links);
                })
                .catch(err => console.log(err));
            },
            makePagination(meta, links) {
                let pagination = {
                    current_page: meta.current_page,
                    last_page: meta.last_page,
                    next_page_url: links.next,
                    prev_page_url: links.prev
                }

                this.pagination =  pagination;
            },
            deleteEmployee(id) {
                if(confirm('Are You Sure?')) {
                    fetch(`api/employee/${id}`, {
                        method: 'delete'
                    })
                    .then(res => res.json())
                    .then(data => {
                        alert();
                    })
                    .catch(err => console.log(err));
                }
            },
            addEmployee() {
                if(this.edit === false) {
                    //Add
                    fetch('api/employee', {
                        method: 'post',
                        // body: JSON.stringyfy(this.employee),

                        headers: {
                            'content-type': 'application/json'
                        }
                    })
                    .then(res =>  res.json())
                    .then(data => {
                        this.employee.employee_no = '';
                        this.employee.last_name = '';
                        this.employee.first_name = '';
                        this.employee.middle_name = '';
                        this.employee.email = '';
                        alert('Employee Added');
                        this.fetchEmployees();
                    })
                    .catch(err => console.log(err));
                } else {
                    // update
                }
            }
        }
    };
</script>

thanks.

0 likes
6 replies
Nameless_0's avatar
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests;
use App\Employee;
use App\Http\Resources\Employee as EmployeeResource;

class EmployeeController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        // Get employees
        $employees = Employee::orderBy('created_at', 'desc')->paginate(7);

        // Return employees as resource
        return EmployeeResource::collection($employees);
    }


    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $employee = $request->isMethod('put') ? Employee::findOrFail($request->employee_id) : new Employee;

        $employee->id = $request->input('employee_id');
        $employee->employee_id = $request->input('employee_id');
        $employee->last_name = $request->input('last_name');
        $employee->first_name = $request->input('first_name');
        $employee->middle_name = $request->input('middle_name');
        $employee->email = $request->input('email');

        if($employee->save()) {
            return new EmployeeResource($employee);
        }

    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        // Get employee info
        $employee = Employee::findOrFail($id);

        //return the single employee as a resource
        return new EmployeeResource($employee);
    }


    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        // Get employee info
        $employee = Employee::findOrFail($id);

        if($employee->delete()){
            return new EmployeeResource($employee);
        }
    }
}

Yorki's avatar
Yorki
Best Answer
Level 11

Looks like you are passing empty body to your controller. Yet you are using employee_no on frontend and employee_id on your backend.

Uncomment and try again

body: JSON.stringyfy(this.employee),

Yet on backend

//change to employee_no
$employee->employee_id = $request->input('employee_no');
Nameless_0's avatar

I tried changing the employee_no to employee_id but it still gives the same error.

Yorki's avatar

You are not sending any data or its nested. See your dump

public function store(Request $request)
{
    dd($request->all());
}

Please or to participate in this conversation.