Liam Liam - 4 months ago 13
PHP Question

Laravel 5 checkbox can only 'change' database input once

I have a list of projects which can be 'completed' or 'not completed' with a checkbox.

Now when a project is not finished and I use the checkbox to mark it is finished, same way other way around it works.

But then for example: I have a unfinished project that I want to mark as finished it works, but then I want to mark it as unfinished again and that wont work. It will stay as 'finished' instead of going back to 'unfinished' again. how can I fix this?

Controller:

class ProjectController extends Controller
{
private $project;

public function __construct(Project $project){

$this->project = $project;

$this->project = $project
->with('user');
}

public function getUsersTotal () {
$project_users = DB::table('users')
->select('browser')
->groupBy('browser')
->get();
}

public function index()
{
$projects = Project::get();

return view('project.index', array('projects' => $projects));
}


public function create()
{
return view('project.create');
}


public function store(CreateProjectRequest $request, Project $project)
{
$project->create($request->all());

return redirect()->route('project.index');
}


public function show($id)
{
//
}


public function edit($id)
{
$project = $this->project->find($id);


return view('project.edit', ['project' => $project, 'id' => 'edit']);
}



public function update(CreateProjectRequest $request, $project)
{
$project = $this->project->find($project);
$project->fill($request->input())->save();

return redirect('project');
}


public function destroy($projectId)
{
$this->project->destroy($projectId);

return redirect('project');
}
}


HTML(Blade):

{!! Form::model($project, ["route"=> ['project.update',$project->id] , "method" => 'PATCH']) !!}

@include('project._form')
<div class="form-group {{ $errors->has('completed') ? 'has-error' : '' }}">
{!! Form::label('name', trans('common.completed'), ['class' => 'form-label']) !!}
{!! Form::checkbox('completed', '1', false, ['class' => '']) !!}
</div>
<br>
<div class="form-group">
{!! Form::submit( trans('common.edit'), ["class"=>"btn btn-primary"]) !!}
</div>
{!! Form::close() !!}

{!! delete_form(['project.destroy', $project->id]) !!}

Answer

You need this just before your checkbox definition:

<input name='completed' type='hidden' value='0'>
{!! Form::checkbox('completed', '1', false, ['class' => '']) !!}

This will make sure that a value of 0 is sent to the application when the checkbox is not checked.