Search code examples
phplaravellaravel-routing

Laravel get the route that do the POST or GET request laravel


I am trying to get the source of the url that does the request POST/GET to a route. For example:

Route::post('/do-something', somethingController@getWhoRequesting);

Then as example, on the view I do ajax or a simple form post to that route, which is from localhost:8888/my-web-view. How do I get the url of who is requesting to my /do-something endpoint? I expect on getWhoRequesting(), but I get the '/my-web-view'.
Thanks in advance


Solution

  • You can get full url from requestin controller using request

    request()->fullUrl();  or $request->fullUrl();
    

    Updates:

    If you want to capture all request then you can create middleware and assign it to all routes

    php artisan make:middleware  RequestCapture
    

    then file will be look like this

    <?php
    
    namespace App\Http\Middleware;
    
    use Closure;
    use Illuminate\Http\Request;
    
    
    class RequestCapture
    {
        /**
         * Handle an incoming request.
         *
         * @param  \Illuminate\Http\Request  $request
         * @param  \Closure  $next
         * @return mixed
         */
        public function handle(Request $request, Closure $next)
        {
    
           //here you can capture all $request for assigned middleware routes
    
            return $next($request);
        }
    }
    

    Also register this middleware in kernal.php in protected $routeMiddleware

     'requestCapture' => \App\Http\Middleware\RequestCapture::class,
    

    then you can assign to routegroup

    Route::group(['middleware' => 'requestCapture'], function () {
    
    });