Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 508
mark Avatar asked Dec 21 '16 18:12

mark


People also ask

How do I return a response in laravel?

Laravel provides several different ways to return response. Response can be sent either from route or from controller. The basic response that can be sent is simple string as shown in the below sample code. This string will be automatically converted to appropriate HTTP response.

What is HTTP request in laravel?

Laravel's Illuminate\Http\Request class provides an object-oriented way to interact with the current HTTP request being handled by your application as well as retrieve the input, cookies, and files that were submitted with the request.


2 Answers

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();
}
like image 110
CIRCLE Avatar answered Sep 21 '22 13:09

CIRCLE


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

like image 25
Marcin Nabiałek Avatar answered Sep 18 '22 13:09

Marcin Nabiałek