Ad

Axios Method To Update Database Field Using Vue.js And Laravel

- 1 answer

I am working on an Axios CRUD application with Laravel and Vue.js component. At the moment I'm getting

"HTTP422: UNPROCESSABLE ENTITY - The request was well-formed but could not be processed due to semantic errors. (XHR)POST - http://127.0.0.1:8000/profile/1/4/false"

in the console log when pressing the button. What should happen is update the is_completed field to true, but currently I cannot connect it to the database, not even with Create (the field is nullable).

CompleteButton.vue

        axios.post('/profile/' + this.userId + '/' + this.item2.id +'/'+ this.item2.is_complete)
            .then(response => {
                this.item2 = ! this.item2;

                console.log(response.data);
            })
            .catch(errors => {
                if (errors.response.item2 == 401) {
                    window.location = '/login';
                }
            }
        );

index.blade.php

<div class="d-flex align-items-center pb-3">
                                                <div class="h4">{{ $task->id }}</div>

                                                <complete-button user-id="{{ $user->id }}" item="{{ $task }}" offautocomplete></follow-button>
                                            </div>

web.php

Route::post('/profile/{user}/{task}/{is_complete}', '[email protected]');

CompleteController.php

<?php

namespace App\Http\Controllers;
use App\Profile;
use App\User;
use App\Task;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;


class CompleteController extends Controller
{
 public function __construct()
 {
    $this->middleware('auth');
 }



 public function store(User $user, Task $task, Request $request)
 {
    // check if the authenticated user can complete the task

    $data = $this->validate($request, [
        'is_complete' => 'required|boolean',
    ]);



    Auth::user()->tasks()->where('id', $task->id)->update([
        'is_complete' => $data['is_complete']
    // mark the task as complete and save it
    ]);

}

}
Ad

Answer

You are mixing up POST and GET syntax in your axios request and your endpoint.

You're therefore not sending any data at all to the POST endpoint - meaning that validation is failing for is_complete as both required and boolean

Try:

axios.post(
    '/profile/' + this.userId + '/' + this.item2.id,
    {is_complete : this.item2.is_complete}
)
//.........
Route::post('/profile/{user}/{task}/', '[email protected]');

When debugging you might find it useful to console.log(error.response.data) so that you can review your validation errors.

Ad
source: stackoverflow.com
Ad