KishorKurian's avatar

Using Response()->json from Helpers

Hello,

I am trying to make a REST API backend for my app.

To keep the API outputs same format from all places, I am using a helper with statis functions, to which I send errors and outputs and the functions prints it for me.

I would like to use response()->json from the helper file. I am not able to. I dont get any errors, but I dont see any outputs either. Should I add something in the use statement to be able to use it?

I made helper class myself. so please let me know whats wrong.

Also Is this a good approach? The backend will have considerable number of controllers which output data, which is why I made a helper instead of formatting it every time,

0 likes
3 replies
Flor's avatar

It's hard to help, without any code snippets.

Are you returning the returned value from your helper class in your controller?

class ResponseController extends Controller
{
    public function index()
    {
        return MyHelperClass::getFormattedResponse();
    }
}

Besides that, it sounds like you could benefit from using transformers. There's an excellent package from The PHP League here: https://fractal.thephpleague.com/transformers/

1 like
KishorKurian's avatar

Sorry for not including the code.

[CODE] class Helper { public static function output($data){ return response()->json(['response' => array('status'=>true,'data'=>$data)]); } } [/CODE]

I am trying to use the response() function from the Helper file, opposed to returning the formatted output back to controller. I am wondering if I should use any use statements to print the response from the helper class itself.

Flor's avatar
Flor
Best Answer
Level 3

A method in a controller MUST return something, otherwise no response is being generated.

The response() method is not setting a global response object, but rather making a ResponseFactory.

Please or to participate in this conversation.