如何在Laravel中使用补丁请求?

编程入门 行业动态 更新时间:2024-10-28 06:21:32
本文介绍了如何在Laravel中使用补丁请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

表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中使用补丁请求?

本文发布于:2023-11-23 09:25:30,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1620933.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:补丁   如何在   Laravel

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!