How to get and validate application/json data in Laravel?

不想你离开。 提交于 2019-12-23 05:07:39

问题


I send data from client to server in application/json content type.

Then I try to take this information in server side like as:

public function register(Request $request)
{

        $data = $request->json()->all();
        var_dump($data); die();
}

It returns me empty array()

Also I tried to validate incoming POST using this:

$validator = Validator::make($request->json()->all(), []);

How to get and validate application/json data in Laravel?

I get POST data like as:

dd($_POST);

array:1 [▼
  "application/json" => "{"id":6,"unique_code":null,"name":"О","secondname":"П","lastname":"Валерьевич","datebirth":"14/10/1991 00:00:00","taxcode":"4545","gender":"1","created_at":null,"file":"C:\\db\\tests\\22-07-2017\\MMM1.TXT","orders":{"profession":"Директор","pacient_id":null,"payment":"1","kind_work":"1,2","factory_name":"FALKO","factory_edrpou":"2020","factory_departament":"IT","status_pass":"1","office_address":"Kiev","unique_code":"0","enterprise_id":"12","status":null},"http_code":null}"
]

回答1:


I have an api I post json to. I have an api end point where I post this json

{ "email":"youremail@triumworks.com", "phone": "phone", "name": "name", "password": "password" } The corresponding controller that handles the request looks like

public function create_account(Request $request){
    $data = json_decode(file_get_contents('php://input'));
    $response = new Responseobject;     
    $array_data = (array)$data;

    $validator = Validator::make($array_data, [
        'name' => 'required|string|max:255',
        'email' => 'required|string|email|max:255|unique:users',
        'password' => 'required|string|min:6',
        'phone' => 'required|string|min:12|max:12|unique:users',
    ]);

    if($validator->fails()){
        $response->status = $response::status_failed;
        $response->code = $response::code_failed;
        foreach ($validator->errors()->getMessages() as $item) {
            array_push($response->messages, $item);
        }   
    }
    else{
        $api_token = str_random(60);
        $user = new User();
        $user->api_token = $api_token;
        $user->name = $data->name;
        $user->email = $data->email;
        $user->phone = $data->phone;
        $user->password = bcrypt($data->password);

        if($user->save()){
            $response->status = $response::status_ok;
            $response->code = $response::code_ok;
            $response->result = $user;
        }           
    }
    return Response::json(
            $response
        );
}

This does the same thing as the one above.

public function create_account(Request $request){
        $response = new Responseobject();

        $validator = Validator::make($request->json()->all(), [
            'name' => 'required|string|max:255',
            'email' => 'required|string|email|max:255|unique:users',
            'password' => 'required|string|min:6',
            'phone' => 'required|string|min:12|max:12|unique:users',
        ]);

        if($validator->fails()){
            $response->status = $response::status_failed;
            $response->code = $response::code_failed;
            foreach ($validator->errors()->getMessages() as $item) {
                array_push($response->messages, $item);
            }   
        }
        else{
            $api_token = str_random(60);
            $user = new User();
            $user->api_token = $api_token;
            $user->name = $data->name;
            $user->email = $data->email;
            $user->phone = $data->phone;
            $user->password = bcrypt($data->password);

            if($user->save()){
                $response->status = $response::status_ok;
                $response->code = $response::code_ok;
                $response->result = $user;
            }           
        }
        return Response::json(
                $response
            );
    }



回答2:


The posted data will end up in the request body parameter bag. You get the data either via $request->all() or $request->request->all().

So the Validator looks like this:

$validator = Validator::make($request->all(), []);

Dive deeper:

Or you can use the validate() method in your controllers. Which look like this:

$this->validate($request->all(), []);

Read more about this in the Laravel docs.

To make things even more complicator, you don't even need to inject the Request instance to your controller. You can use the request() helper function. The register method then looks like this:

public function register()
{
    $this->validate(request()->all(), [
        'email' => 'required|email',
        'password' => 'required|min:6|confirmed',
    ]);
}


来源:https://stackoverflow.com/questions/45255156/how-to-get-and-validate-application-json-data-in-laravel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!