项目可以具有不同的状态。选中该复选框,我试图将项目的状态从已请求(1)切换为已接受(2)。如果未选中该复选框,则状态为1,选中状态为2。
当我选中复选框时,我得到了419,但这通常与令牌有关,但是我添加了@csfr字段。为什么状态在数据库中未更改? 感谢您的帮助。
@foreach ($projects as $project)
<tbody>
<tr>
<form action="/projects/plan" method="post" id="statusForm">
@csrf
<input name="id" type="hidden" value="{{$project->id}}">
<td>
<input type="hidden" value="{{$project->status}}" name="status">
<input {{isset($project['status']) && $project['status'] == '2' ? 'checked' : ''}}
value="{{$project->status}}" type="checkbox" name="status"
onchange="document.getElementById('statusForm').submit()"
>
</td>
</form>
<td>{{$project->applicant_name}}</td>
<td>{{$project->project_name}}</td>
<td><a href="/events/{{$projects->id}}/edit" class="btn btn-secondary btn-sm" role="button">Project Details</a></td>
</tr>
</tbody>
@endforeach
const STATUS_requested = 1;
const STATUS_ACCEPTED = 2;
public function updateStatus( $status )
{
$this->update([
'status' => $status
]);
$this->refresh();
return $this;
}
public function projectAccept() {
return $this->updateStatus( self::STATUS_ACCEPTED );
}
public function plan(Request $request)
{
dd('hello');
Event::find($request->id)->projectAccept();
return Project::STATUS_ACCEPTED;
}
// Update status project
Route::post('/projects/plan', 'ProjectsController@plan');
答案 0 :(得分:1)
首先,当您有多个具有相同ID的DOMS时,无法按ID document.getElementById('statusForm').submit()
进行选择。
将循环更改为类似的内容
@foreach ($projects as $project)
<tbody>
<tr>
<td>
<form action="/projects/plan" method="post" id="statusForm{{$project->id}}">
@csrf
<input name="id" type="hidden" value="{{$project->id}}">
<input {{isset($project['status']) && $project['status'] == '2' ? 'checked' : ''}}
value="2" type="checkbox" name="status"
onchange="document.getElementById('statusForm{{$project->id}}').submit()"
>
</form>
</td>
<td>{{$project->applicant_name}}</td>
<td>{{$project->project_name}}</td>
<td><a href="/events/{{$projects->id}}/edit" class="btn btn-secondary btn-sm" role="button">Project Details</a></td>
</tr>
</tbody>
@endforeach
现在,复选框仅在被选中时才会以表格的形式发送,因此该输入不需要变量值
<input {{isset($project['status']) && $project['status'] == '2' ? 'checked' : ''}}
value="2" type="checkbox" name="status"
onchange="document.getElementById('statusForm{{$project->id}}').submit()"
>
最后,当您恢复输入status
时,请为未选中的输入设置默认值(您可以使用此输入删除隐藏的输入)。或者像您所做的那样,设置一个隐藏的输入,将其与每次发送的原始值一起发送。两种解决方案都是完美的。
public function plan(Request $request)
{
$status = $request->input('status', Project::STATUS_requested);
Event::find($request->id)->projectAccept();
return Project::STATUS_ACCEPTED;
}
这样,如果选中它,它将为2(在请求中),否则,默认值将为1。