Rizki Hadiaturrasyid
Rizki Hadiaturrasyid

Reputation: 448

Laravel (Request $request) handling how to check if input is in the correct json format?

So I'm building an api that accepts json input, and catching it in the controller with Request:

{
    "val1": "11",
    "val2": "1000",
    "val3": "1001010",
    "val4": "1001"
}

However I need to catch a condition when the user didn't use proper json, say like this:

{
    "val1": "11",
    "val2": "1000",
    "val3": "1001010"
    "val4": "1001"
}

When I return $request on wrong input format, I got empty array. However I have tried using isset(), empty(), count() on request but it still didn't check the parameters.

public function foo(Request $request)
{
   if(jsoniswrong($request)){return 'false';}
}

I need a way to check the request variable without having to call each values, how do I do this?

edit: I ended up using this which is simpler. I just realized in Laravel, empty($request) will never return true because even on a bad request it still have objects other than the actual input data. To get the input data, use all(). This solved my problem.

    if(empty($request->all())){
        return false;
    }

Upvotes: 0

Views: 2398

Answers (1)

thisiskelvin
thisiskelvin

Reputation: 4202

You may validate an incoming request for json using the validate() method. You can achieve this by doing the following:

public function foo(Request $request)
{
    $data = $request->validate([
        'json' => 'required|json'
    ]);

    // continue process
}

Here, we use the required rule to make sure that the json has been passed. We then use the json rule which checks if valid json has been passed. A | is used to separate validation rules.

If the json is not valid, data about the error will be returned.

Please note, you must name the field/key of the incoming json data the same as the key within the validate() array. e.g. if the field/key is called data it must be ['data' => 'required|json'].

Upvotes: 1

Related Questions