Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

behzad's avatar

return response for a controller action in another class

Imagine I have a PostController as follows:

class PostsController extends \App\Http\Controllers\Controller
{
    public function store(Request $request) {

        $newClass = new myNewClass();
        $newClass->check();

        // ... 
        // continue to store the post
        // ...     

    }
}

Now I want to $newClass->check() stops the action if something I'm checking there happens. this is just a sample code and the behavior of the mentioned methods are more than just that.

in my check method I have:

class MyNewClass
{
    public function check() {

        // I want to send the response directly from here
        // but it doesn't work
        // I tried:
        // return response()->json(['error' => 'auth error'], 403);
        // the line above is not working, that's all I want
        // NOTE: abort(403) works here
        // NOTE: dd('xxxxx') works here
        // but response() doesn't

    }
}

I can fix this by returning the value in my PostsController:

return $newClass->check();

But this always stops the store method and returns.

How can I achieve this?

P.S: I want to send a JSON response in my check() method, I don't want that logic in my controller and that's why I am doing this.

0 likes
1 reply
tykus's avatar
tykus
Best Answer
Level 104

You can't return responses from down the stack (it will simply return controller to wherever it was called from); however, you could throw a custom exception in the check() method and then add a Handler / render method to return the desired response.

Please or to participate in this conversation.