For our Task attributes we have the following: task_id as primary key, user_id, stage_id and project_id as foreign keys, completed as boolean and a description. Our goal is to display the tasks under a project and by checking the checkbox right next to them, it should mark them as complete. The problem is in our database the ‘complete’ status doesnt change. We are using PhpMyAdmin. We have a separate controller called ProjectTasksController for handling the logic and a form in our show.blade.php view for sending the request. Any help would be greatly appreciated.
@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 AppHttpControllers;
use IlluminateHttpRequest;
use AppTask;
class ProjectTasksController extends Controller{
public function update(Task $task)
{
$task->update([
'completed' => request()->has('completed')
]);
return back();
}
}
<?php
namespace App;
use IlluminateDatabaseEloquentModel;
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');
2
Answers
If you want to use route model binding the name of your parameter in the update function should match the route parameter:
Replace
protected $primaryKey = ['task_id]';
withprotected $primaryKey ='task_id'
in the Task model. It should be a string, not an array.Your controller method was not correct, hint of
Task $task
is just a instance ofTask
not the collection or a single Model.And you have not specify yourRequest $request
to get this workrequest()->has('completed')
in method arguments.You need to edit your method in following way: