Как обновить пользователя через api в laravel - PullRequest
0 голосов
/ 13 февраля 2020
I'm trying to update user through api, and this is the function.

PUT-запрос http://20a11140.ngrok.io/api/userregister/24 для пользователя с идентификатором 24, например. Я использую почтальон для тестирования. Когда я передаю отредактированные данные, с именем включительно

public function update(Request $request, $id)
{
        $validator = Validator::make($request->all(), [
            'name' => 'required|string|max:255',
            'email' => 'required|string|email|max:255|unique:users',
            'password' => 'string|min:6|confirmed',
            'phone' => 'string|min:6',
            'Age' => 'string',
            'Blood' => 'string',
            'Gender' => 'string',
            'Height' => 'string',
            'Weight' => 'string',
            'record' => 'string'
        ]);

    if($validator->fails()){
            return response()->json($validator->errors()->toJson(), 400);
}

        $doc = User::find($id);

        if($request->hasFile('picture')){
            // Get filename with the extension
            $filenameWithExt = $request->file('picture')->getClientOriginalName();
            // Get just filename
            $filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
            // Get just ext
            $extension = $request->file('picture')->getClientOriginalExtension();
            // Filename to store
            $fileNameToStore= $filename.'_'.time().'.'.$extension;
            // Upload Image
            $path = $request->file('picture')->storeAs('public/images', $fileNameToStore);
        } else {
            $fileNameToStore = 'noimage.jpg';
        }

        $doc->name = $request->input('name');
          $doc->email = $request->input('email');
          $doc->phone = $request->input('phone');
          if($request->hasFile('picture')){
            $doc->picture = $fileNameToStore;
            }



           $doc->save();

        return response()->json([
            'message' => 'Success',

        ]);

    }

Когда я передаю отредактированные данные, с именем включительно и электронной почтой, и каждой необходимой информацией. Когда я запускаю этот код, я получаю это

"{\"name\":[\"The name field is required.\"],\"email\":[\"The email field is required.\"]}"

В чем здесь проблема?

1 Ответ

0 голосов
/ 13 февраля 2020

Где-то вы не правы при отправке данных.

Если вы используете промежуточное ПО API, вам придется отправлять данные с Body Raw Json с помощью Postman.

{
    "info": {
        "_postman_id": "9bc0d91b-83e7-4ccf-a561-ac191c21e869",
        "name": "Laravel",
        "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json"
    },
    "item": [
        {
            "name": "http://20a11140.ngrok.io/api/userregister/24",
            "request": {
                "method": "PUT",
                "header": [
                    {
                        "key": "Content-Type",
                        "name": "Content-Type",
                        "value": "application/json",
                        "type": "text"
                    }
                ],
                "body": {
                    "mode": "raw",
                    "raw": "{\n\t\"name\" : \"BHaskar Rajoriya\",\n\t\"email\" : \"brn.rajoriya@gmail.com\"\n}",
                    "options": {
                        "raw": {
                            "language": "json"
                        }
                    }
                },
                "url": {
                    "raw": "http://20a11140.ngrok.io/api/userregister/24",
                    "protocol": "http",
                    "host": [
                        "20a11140",
                        "ngrok",
                        "io"
                    ],
                    "path": [
                        "api",
                        "userregister",
                        "24"
                    ]
                }
            },
            "response": []
        }
    ],
    "protocolProfileBehavior": {}
}

Используйте эту коллекцию почтальонов.

...