user9048585
user9048585

Reputation:

Calling a controller method from laravel middleware

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?

Upvotes: 4

Views: 4178

Answers (3)

Yevgeniy Afanasyev
Yevgeniy Afanasyev

Reputation: 41360

in your middleware

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

tested on laravel 9

Upvotes: 1

Top-Master
Top-Master

Reputation: 8751

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.

Upvotes: 4

Jignesh Joisar
Jignesh Joisar

Reputation: 15115

try this one in middleware by create of your controller

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

Upvotes: 2

Related Questions