使用 vue.js 和 Laravel 更新数据库字段的 Axios 方法

Axios method to update database field using vue.js and Laravel

我正在开发一个带有 Laravel 和 Vue.js 组件的 Axios CRUD 应用程序。目前我得到

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

按下按钮时在控制台日志中。应该发生的是将 is_completed 字段更新为 true,但目前我无法将其连接到数据库,甚至无法使用 Create(该字段可为空)。

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

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
    ]);

}

}

您在 axios request 和端点中混淆了 POST 和 GET 语法。

因此,您根本没有向 POST 端点发送任何数据 - 这意味着 is_complete 的验证失败,因为 requiredboolean

尝试:

axios.post(
    '/profile/' + this.userId + '/' + this.item2.id,
    {is_complete : this.item2.is_complete}
)
//.........
Route::post('/profile/{user}/{task}/', 'CompleteController@store');

调试时,您可能会发现 console.log(error.response.data) 很有用,这样您就可以查看验证错误。