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.
May 3, 2018
1
Level 2
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.
Level 104
Please or to participate in this conversation.