Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
699 views
in Technique[技术] by (71.8m points)

php - How to use patch request in Laravel?

There is entity User that is stoted in table Users

Some fields in this table are null by default.

I need to update these fields and set not null data.

For this I try to use PATCH method in Laravel:

Routing:

Route::patch('users/update', 'UsersController@update');

Controller:

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]);

    }

Does it mean that I can pass any data to update? Should I pass $id parameter to routing and controller relatively?

How to use right handler for PATCH method in Laravel?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

your route is:

Route::patch('users/update', 'UsersController@update');

replace your route with following route that use for all CRUD opration:

Route::resource('users', 'UsersController');

if you use ajax for submit data then replace your type and url with following:

type: "patch",
url: "{{url('/')}}users/" + id,

if you don't use ajax than use following:

<form method="POST" action="{{route('users.update',['id' => $id])}}">
    {{csrf_field()}}
    {{ method_field('PATCH') }}
</form>

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...