問題描述
Users
此表中的某些字段默認為空.
Some fields in this table are null by default.
我需要更新這些字段并設置非空數據.
I need to update these fields and set not null data.
為此,我嘗試在 Laravel 中使用 PATCH
方法:
For this I try to use PATCH
method in Laravel:
路由:
Route::patch('users/update', 'UsersController@update');
控制器:
public function update(Request $request, $id)
{
$validator = Validator::make($request->all(), [
"name" => 'required|string|min:3|max:50',
"email_work" => 'email|max:255|unique:users',
"surname" => 'required|string|min:3|max:50',
"tel" => 'required|numeric|size:11',
"country" => 'required|integer',
"region" => 'required|integer',
"city" => 'required|integer'
]);
if ($validator->fails()) {
return response()->json(["message" => $validator->errors()->all()], 400);
}
$user = User::where("user_id", $id)->update([
"name" => $request->name,
"surname" => $request->surname,
"tel" => $request->tel,
"country" => $request->country,
"city" => $request->city,
"region" => $request->region,
"email_work" => $request->email
]);
return response()->json(["user" => $user]);
}
這是否意味著我可以傳遞任何數據進行更新?我應該將 $id
參數相對傳遞給路由和控制器嗎?
Does it mean that I can pass any data to update?
Should I pass $id
parameter to routing and controller relatively?
如何在 Laravel 中為 PATCH 方法使用正確的處理程序?
How to use right handler for PATCH method in Laravel?
推薦答案
你的路線是:
Route::patch('users/update', 'UsersController@update');
用以下用于所有 CRUD 操作的路由替換你的路由:
replace your route with following route that use for all CRUD opration:
Route::resource('users', 'UsersController');
如果您使用 ajax 提交數據,則將您的類型和網址替換為以下內容:
if you use ajax for submit data then replace your type and url with following:
type: "patch",
url: "{{url('/')}}users/" + id,
如果您不使用 ajax,請使用以下內容:
if you don't use ajax than use following:
<form method="POST" action="{{route('users.update',['id' => $id])}}">
{{csrf_field()}}
{{ method_field('PATCH') }}
</form>
更新:在 5.6 版之后,您可以在任何刀片文件中對上述函數使用這些語法:
update: after version 5.6 you can use these syntax for above functions in any blade file:
<form method="POST" action="{{route('users.update',['id' => $id])}}>
@csrf
@method('PATCH')
</form>
這篇關于如何在 Laravel 中使用補丁請求?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!