shahajahancse's avatar

How to solve 422 (Unprocessable Entity), laravel and vuejsI am using Laravel 6.2 and 2.5.17, to communicate with a mysql database. When I am able to properly POST request send on the without body, I get error 422 (Unprocessable Entity)

I am using Laravel 6.2 and vuejs 2.5.17, to communicate with a mysql database. When I am able to properly POST request send on the without body, I get error 422 (Unprocessable Entity)

My API Controller:

public function store(Request $request)
{
    $this->validate($request, [
        'name' => 'required',
        'email' => 'required|email|unique:customers',
        'phone' => 'required|numeric',
        'address' => 'required',
        'total' => 'required|numeric'
    ]);

    $customer = new Customer();
    $customer->name = $request->name;
    $customer->email = $request->email;
    $customer->phone = $request->phone;
    $customer->address = $request->address;
    $customer->total = $request->total;
    $customer->save();                      //save data 
    return new CustomerResource($customer);     // save and return
}

// And componentsVue.vue:

...... ......
Add New Customer
× Name Email Address Close Save changes export default { data(){ return{ query: '', queryFeild: 'name', customers: [], form : new Form({ id : '', name: '', email: '', phone: '', address: '', total: '', }), pagination:{ current_page: 1, } } }, watch:{ query:function (newQ, old) { if (newQ === '') { this.getData(); } else{ // console.log(newQ) // to check saerch data this.searchData() } } }, mounted() { console.log('Component mounted.') this.getData(); }, methods: { getData(){ this.$Progress.start() axios.get('/api/customers?page='+this.pagination.current_page) .then(response => { this.customers = response.data.data this.pagination = response.data.meta this.$Progress.finish() }) .catch(e => { console.log(e) this.$Progress.fail() }) }, create(){ $('#customerModal').modal('show') }, store(){ // data store/insert to add customer this.$Progress.start() this.form.busy = true this.form.post('/api/customers') .then(response => { this.getData() $('#customerModal').modal('hide') if (this.form.successful) { this.$Progress.finish() this.$snotify.success('Customer Successfully Saved','Success') } else { this.$Progress.fail() this.snotify.error("Ops! Something went wrong try again leter", "Error") } }) .catch(error => { this.$Progress.fail() if(error.code == 422){ console.log(error.data) } }) } } }
0 likes
2 replies
bobbybouwmann's avatar
Level 88

Well, if you send no body to the form the validation will fail, right? You say that the name, email, .etc are required. If you don't put them in the body the validation fails and it returns a 422. This is expected behavior.

Please or to participate in this conversation.