user2890725
user2890725

Reputation: 88

Calling laravel controller inside a route

I've Laravel route with GET & POST as below

Route::get("test1","Api\TestController@test1");
Route::post("test1","Api\TestController@test1");

Now I'm trying to check some condition & if it remain true then I want to call controller else i want to show error without even going into controller.

Like:

Route::get("test1",function(){

$aaa=$_SERVER['REQUEST_URI'];
if(preg_match("/sender_id=TEST/is", $aaa)){

@Call_controller: "Api\TestController@test1" 

}else{
echo "some error found"; die();}

});

How to call controller inside function of route.

I don't want to check this in controller because its a API & when i'm getting 10000+ hits per second, calling a function inside laravel load multiple dependences resulting wastage of server resources.

Upvotes: 1

Views: 83

Answers (2)

Abdulla Nilam
Abdulla Nilam

Reputation: 38584

Since both your route functions are the same, you can use middleware.

Create check middleware php artisan make:middleware check

class check
{
    public function handle($request, Closure $next)
    {
        if(preg_match("/sender_id=TEST/is", $request->getUri())) {
            return $next($request);
        }
        else{
            return "some error found";
        }
    }
}

And in route

Route::group(['middleware' => 'check'], function () {
    Route::get("test1","Api\TestController@test1");
    Route::post("test1","Api\TestController@test1");
});

Upvotes: 0

Aranya Sen
Aranya Sen

Reputation: 1094

While you can call the controller using (new Api\TestController())->test1(), the right way to do is:

  • Create a middleware (say "MyMiddleware") and add your logic in the handle() method:
public function handle($request, Closure $next)
{
    $aaa=$_SERVER['REQUEST_URI'];
    if (preg_match("/sender_id=TEST/is", $aaa)) {
      return $next($request);
    }
    abort(403);
}
  • Now use the middleware in the route:
Route::get("test1","Api\TestController@test1")->middleware(MyMiddleware::class);

Upvotes: 1

Related Questions