我试图让按钮在点击时将查询传递给数据库。我希望在Controller中设置此设置,同时存储请求和删除请求。我能够使用store()和destroy()写入数据库,但是我的edit()函数给我带来路由故障。使用控制器编辑记录的最佳方法是什么?你将如何构建edit()函数?或者......我应该使用Update()函数吗?我是Laravel / PHP的初学者,如果可以,请解释一下你的答案。谢谢!!
概述:该项目是员工记录表。我想点击一个改变员工就业状况的按钮。我已经有按钮添加新员工,删除和员工使用同一个控制器。
Route::resource('employees', 'EmployeeController');
$workers = DB::table('employees')->get();
@foreach($workers as $employee)
{!! Form::open(array(
'method' => 'edit',
'route' => [ 'employees.edit', $employee->id]
)
)
!!}
<button type="submit">Release </button>
{!! Form::close() !!}
@endforeach
public function store(Request $request)
{
// Confirm Both Fields Are Not Empty
$this->validate($request, [
'first_name' => 'required',
'last_name' => 'required',
]);
//Add a new employee using the request data
$employee = new Employee;
$employee->first_name = request('first_name');
$employee->last_name = request('last_name');
$employee->position = request('position');
$employee->salary = request('salary');
$employee->hire_date = request('hire_date');
//$employee->attach = request('attach');
//Save it to the database
$employee->save();
//And then redirect back to the Employees page
return redirect('/employees');
}
public function destroy($id)
{
$employee = Employee::find($id);
$destroysignal = $employee->delete();
if($destroysignal) {
return redirect('employees');
}
}
答案 0 :(得分:0)
您不会编辑记录,而是更新记录。在您的情况下,您需要在控制器中使用update()函数
public function update(Request $request, $id)
{
$employee = Employee::findOrFail($id);
$employee->employment_status = true; //or false or whatever your statuses are
$employee->update();
return redirect()->back()->with('message', 'Employee updated!');
}
在您的表单中,使用更新路由
{!! Form::model($employee, [
'method' => 'PATCH',
'route' => ['employees.update', $employee->id]])
!!}
<button type="submit">Release </button>
{!! Form::close() !!}
使用资源路由时,'route' => [ 'employees.edit', $employee->id]
最希望打开要编辑对象的页面。并且路由将绑定到控制器的edit($id)
功能。
据说,编辑路线不需要表格。一个简单的锚点就可以了
<a href="{{ route('employees.edit', $employee->id) }}">Edit Employee</a>