skip to Main Content

I’ve Laravel route with GET & POST as below

Route::get("test1","ApiTestController@test1");
Route::post("test1","ApiTestController@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: "ApiTestController@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.

  • Same has to be done with GET & POST

2

Answers


  1. While you can call the controller using (new ApiTestController())->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","ApiTestController@test1")->middleware(MyMiddleware::class);
    
    Login or Signup to reply.
  2. 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","ApiTestController@test1");
        Route::post("test1","ApiTestController@test1");
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search