php - Laravel Delete and Update
问题描述
I created a Post and a Get Request, Looks like this:
public function getAllCustomer()
{
$customer = \App\model\Customer::get();
return $view = View::make('test')->with('customer', $customer);
}
public function addNewCustomer(Request $request)
{
$validatedData = $request->validate([
'Title' => 'required',
'Name' => 'required|max:255'
]);
return \app\model\Customer::create($request->all());
}
So I can read all the data and create some new one, but now I want to delete them and/or update them, I couldnt find something really helpful, I would be very thankful for some help!
解决方案
for updating you can define a route like this
Route::put('customer/{customer}' , 'CustomerController@update');
you should define a method_field('put') in your form and create a function called update in your controller
pulblic function update (Request $request , Customer $customer){
$customer->update($request->all());
}
to update the fields that you want to be updated, you have to add them to $fillable array in your customer model, read about Mass Assignment in laravel and that because all Eloquent models are protected against mass-assignment by default.
for delete : route:
Route::delete('customer/{customer} , 'CustomerController@destroy');
a function for deleteing customer in your controller
public function destroy (Customer $customer){
$customer->delete();
}
and add method_field('delete') to your form
Form example:
<form action="{{url("customer/{$customer->id}")}}"
method="post">
{{method_field('delete')}}
//Html Elements Here
</form>
after you get familiar with routes and controller you can make benefits of using
Route::resource('customer','CustomerController');
which will create all necessary route for you
Edited: please note that {customer} in route should be the id of the Customer you want to update or delete
推荐阅读
- google-app-engine - 是否可以在 App Engine 标准环境中使用 Google Cloud CDN?
- node.js - Mongoose - 使本地数据库与远程数据库保持同步
- azure - 在生成期间使用系统 OAuth 令牌时,Azure DevOps REST API 返回 403
- jsf - 调用有状态会话 Bean 后目标不可达
- r - 在 R 中指定线性模型,没有带对比的截距
- php - 试图在新窗口中打开点击元素
- javascript - 为什么 document.getElementByID 返回 null?
- azure-cosmosdb - 是否可以读取一些值,然后在更新中使用该值?
- excel - 在工作表退出时清除数据透视表上的过滤器的 VBA 代码
- c# - 使用正则表达式和硒验证邮政编码