4

I have a method in my base controller.php that formats all my responses to how I like it like so;

public function sendError($error, $errorMessages = [], $code = 404)
{
    $response = [
        'success' => false,
        'message' => $error,
    ];

    if (!empty($errorMessages)) {
        $response['data'] = $errorMessages;
    }

    return response()->json($response, $code);
}

If I am calling it from another controller, i simply just call

return $this->sendError('Validation Error', $validator->errors(), 400);

But i am also using middleware for my JWT-Auth. Instead of re-writing the method, is there any way to call this controller method from inside middleware?

3
  • Maybe you can build the controller instance using app(YourControllerNameHere::class), and call the method using call_user_func_array. Commented Oct 4, 2018 at 2:33
  • return (new yourChildController)->sendError('xyz errro',[],400) create instance of controller Commented Oct 4, 2018 at 5:26
  • @JigneshJoisar that has worked, is there any chance your could add an answer so that i can accept it? Commented Oct 4, 2018 at 5:47

3 Answers 3

4

First get the existing instance:

use Illuminate\Support\Facades\Route;

// ...

$myController = Route::getCurrentRoute()->getController();

Then call as you would normally, in OP's case:

return $myController->sendError('My error message.', [], 400);

Note that above is tested with Laravel 6.x release.

Sign up to request clarification or add additional context in comments.

Comments

2

try this one in middleware by create of your controller

return (new yourChildController)->sendError('xyz errro',[],400)

Comments

1

in your middleware

$request
        ->route()
        ->getController()
        ->myMethodOnMyController($data);

tested on laravel 9

2 Comments

This is pretty much the same as the other recent answer, just uses $request->route() instead of Route::getCurrentRoute() facade method.
ha-ha-ha. You missed a year. The other answer is a year old. But I upvoted it. You can upvote both or the best one. I personally don't like Facades, because it is a hidden dependency. And I tested it on on Laravel 9