Как переключить поле базы данных логических значений в Laravel - PullRequest
0 голосов
/ 06 февраля 2020

Я создаю список задач с кнопкой «Завершено» для каждой задачи, которая должна иметь возможность сбросить поле is_completed с true на false в таблице задач. Идентификатор пользователя передается через форму, и vue. js изменяет статус текста кнопки. Моя проблема связана с функцией хранилища файлов контроллера, как показано в коде ниже. В настоящее время текст кнопки не изменяется и в базе данных нет изменений is_completed. Кнопка вообще не реагирует, и в консоли браузера нет обновлений.

index.blade. php

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

<follow-button user-id="{{ $user->id }}" follows="{{ $follows }}"></follow-button>
</div>

web. php

Route::post('follow/{user}', 'FollowsController@store');

Кнопка Follow. vue

<template>
  <div>
    <button class="btn btn-primary ml-4" @click="followUser" v-text="buttonText"></button>
  </div>
</template>

<script>
export default {
    props: ['userId', 'follows'],

    mounted() {
        console.log('Component mounted.')
    },

    data: function () {
        return {
            status: this.follows,
        }
    },

    methods: {
        followUser() {
            axios.post('/follow/' + this.userId)
                .then(response => {
                    this.status = ! this.status;

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

    computed: {
        buttonText() {
            return (this.status) ? 'Unfollow' : 'Follow';
        }
    }
}
</script>

FollowsController. php

namespace App\Http\Controllers;

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

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

    public function store(User $user)
    {
        return auth()->user()->following()->toggle($user->task);
    }
}

Задача. php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Task extends Model
{

protected $casts = [
    'is_complete' => 'boolean',
];


protected $fillable = [
    'title',
    'is_complete',
];


public function user()
{
    return $this->belongsTo(User::class);
}
}

Пользователь. php

<?php
namespace App;



use App\Mail\NewUserWelcomeMail;

use Illuminate\Notifications\Notifiable;

use Illuminate\Contracts\Auth\MustVerifyEmail;

use Illuminate\Foundation\Auth\User as Authenticatable;

use Illuminate\Support\Facades\Mail;



class User extends Authenticatable

{

use Notifiable;



protected $fillable = [

    'username', 'password',

];




protected $hidden = [

    'password', 'remember_token',

];





protected $casts = [

    'email_verified_at' => 'datetime',

];



protected static function boot()

{

    parent::boot();



    static::created(function ($user) {

        $user->profile()->create([

            'title' => $user->username,

        ]);




    });

}



public function posts()

{

    return $this->hasMany(Post::class)->orderBy('created_at', 'DESC');

}



public function following()

{

    return $this->belongsToMany(Profile::class);

}



public function profile()

{

    return $this->hasOne(Profile::class);

}





public function tasks()
{
    return $this->hasMany(Task::class);
}

}
class User extends Authenticatable

{

use Notifiable;





protected $fillable = [

    'username', 'password',

];


protected $hidden = [

    'password', 'remember_token',

];


protected $casts = [

    'email_verified_at' => 'datetime',

];



protected static function boot()

{

    parent::boot();



    static::created(function ($user) {

        $user->profile()->create([

            'title' => $user->username,

        ]);




    });

}



public function posts()

{

    return $this->hasMany(Post::class)->orderBy('created_at', 'DESC');

}



public function following()

{

    return $this->belongsToMany(Profile::class);

}



public function profile()

{

    return $this->hasOne(Profile::class);

}





public function tasks()
{
    return $this->hasMany(Task::class);
}

}
...