对于我们的Task属性,我们具有以下内容:task_id作为主键,user_id,stage_id和project_id作为外键,以布尔值和说明形式完成。我们的目标是显示项目下的任务,并通过选中它们旁边的复选框将其标记为完成。问题是在我们的数据库中,“完成”状态没有改变。我们正在使用PhpMyAdmin。我们有一个名为ProjectTasksController的单独控制器来处理逻辑,并在show.blade.php视图中有一个表单用于发送请求。任何帮助将不胜感激。
@extends('layouts.app')
@section('content')
<div class="display-3">{{$project->name}}</div>
<a class="nav-link" href="/projects/{{$project->project_id}}/edit"><i class="material-icons">edit</i></a>
@if ($project->image)
<div class="row">
<div class="col-12">
<img src="{{ asset('storage/' . $project->image) }}" alt="...." class="img-thumbnail">
</div>
</div>
@elseif(!$project->image)
no image
@endif
@if ($project->tasks->count())
<div>
@foreach ($project->tasks as $task)
<div>
<form method="POST" action="/tasks/{{$task->task_id}}">
{{method_field('PATCH')}} {{-- @method('PATCH') --}}
@csrf
<label class="checkbox {{$task->completed ? 'is_complete' : ''}} " for="completed">
<input type="checkbox" name="completed" onChange="this.form.submit()" {{$task->completed ? 'checked' : ''}} >
{{$task->description}}
</label>
</form>
</div>
@endforeach
</div>
@endif
@endsection
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Task;
class ProjectTasksController extends Controller{
public function update(Task $task)
{
$task->update([
'completed' => request()->has('completed')
]);
return back();
}
}
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Task extends Model
{
protected $guarded = [];
protected $primarykey = ['task_id'];
protected $fillable = ['user_id','stage_id','project_id','completed','description'];
public function stage(){
return $this->belongsTo(Stage::class);
}
public function user(){
return $this->belongsTo(User::class);
}
public function project(){
return $this->belongsTo(Project::class);
}
}
{
_method: "PATCH",
_token: "ljiwu8bEtAkRqSUOXllmaRbSujavHNYNRJR5TMcy",
completed: "on"
}
Route::patch('/tasks/{task_id}', 'ProjectTasksController@update');
答案 0 :(得分:2)
您的控制器方法不正确,提示Task $task
只是Task
的实例,不是集合或单个Model。并且您没有指定Request $request
来完成这项工作方法参数中的request()->has('completed')
。您需要按以下方式编辑方法:
public function update(Request $request,$task_id)
{
Task::find($task_id)->update([
'completed' => $request->has('completed')
]);
return back();
}
注意:
$request->has('completed')
将返回Boolean
;如果您想要确切的值,则需要以$request->get('completed')
答案 1 :(得分:0)
如果要使用路由模型绑定,则更新功能中参数的名称应与route参数匹配:
Route::patch('/tasks/{task}', 'ProjectTasksController@update');
在任务模型中用protected $primaryKey = ['task_id]';
替换protected $primaryKey ='task_id'
。它应该是字符串,而不是数组。