mark
mark

Reputation: 228

For Laravel, how to return a response to client in a inner function

I'm building an API using laravel, the issue is when the client requests my API by calling create() function, and the create() function will call a getValidatedData() function which I want to return validation errors to the client if validation fails or return the validated data to insert database if validation passes, my getValidatedData function is like below so far:

protected function getValidatedData(array $data)
{
    // don't format this class since the rule:in should avoid space
    $validator = Validator::make($data, [
        'ID' => 'required',
        'weight' => 'required',
    ]);
    if ($validator->fails()) {
        exit(Response::make(['message' => 'validation fails', 'errors' => $validator->errors()]));
    }
    return $data;
}

I don't think exit() is a good way to return the errors message to clients. Are there any other ways I can return the laravel response to clients directly in an inner function? Use throwing Exception?

Upvotes: 8

Views: 6880

Answers (4)

Romek
Romek

Reputation: 334

I know this question is old but it might still help someone: I tried returning a response from my inner function like this as suggested by the other answers:

response()->json([
  'error' => true,
  'error_message' => 'Error Message',
], 404)->send();
exit;

But I stumbled upon problems with CORS whenever I got responses back like this, because the CORS headers were missing. I'm now using the throwResponse method and it seems to be working without issues.

response()->json([
  'error' => true,
  'error_message' => 'Error Message',
], 404)->throwResponse();

Upvotes: 1

Amir
Amir

Reputation: 340

You can use this method

 public static function Validate($request ,$rolse)
{
    // validation data
    $validator = Validator::make($request->all(),$rolse);

    $errors = $validator->getMessageBag()->toArray();
    $first_error = array_key_first($errors);
    if (count($errors) > 0)
        return  'invalid input params , ' . $errors[$first_error][0];

    return false;

}

in controller :

   $validate = ValidationHelper::Validate($request,
        ['title' => 'required']);

    if ($validate)
         return response()->json(['message' =>'validation fails' , 'error'=> $validate], 403);

Upvotes: 0

CIRCLE
CIRCLE

Reputation: 4879

This was what worked for me in Laravel 5.4

protected function innerFunction()
{
    $params = [
        'error' => 'inner_error_code',
        'error_description' => 'inner error full description'
    ];
    response()->json($params, 503)->send();
}

Upvotes: 13

Marcin Nabiałek
Marcin Nabiałek

Reputation: 111839

What you can do is using send method, so you can use:

if ($validator->fails()) {
    Response::make(['message' => 'validation fails', 'errors' => $validator->errors()])->send();
}

but be aware this is not the best solution, better would be for example throwing exception with those data and adding handling it in Handler class.

EDIT

As sample of usage:

public function index()
{
    $this->xxx();
}

protected function xxx()
{
    \Response::make(['message' => 'validation fails', 'errors' => ['b']])->send();
    dd('xxx');
}

assuming that index method is method in controller you will get as response json and dd('xxx'); won't be executed

Upvotes: 3

Related Questions