Ashik Basheer
Ashik Basheer

Reputation: 1601

Laravel 5: cannot pass data from Middleware to Controller

I am sending an ajax request with GET method to a controller

Route::get('test', ['Middleware' => 'TestFilter', 'uses' => 'HomeController@index']);

The Middleware:

public function handle($request, Closure $next)
{
    return $next($request); //This does not seem to pass $request to HomeController
}

In the index() method of HomeController I am trying to return $request but the page throws error

'Undefined variable: request' in D:\Apps\apilab\app\Http\Controllers\HomeController.php

I am simply returning $request in HomeController

class HomeController extends Controller {
  public function index() {
    return $request;
  }
}

How do I pass the request variable to HomeController@index so that I can continue processing?? I am exhausted of trying various methods...

Upvotes: 2

Views: 2543

Answers (1)

Laurence
Laurence

Reputation: 60048

Your code is incorrect. You are returning twice - but only the first return will ever be processed.

Once your middleware is finished - just pass the $next($request) along - so it can be handled by the remainder of the framework

public function handle($request, Closure $next)
{
    return $next($request);
}

Then in your controller

class HomeController extends Controller {
  public function index(Request $request) {
    return $request;
  }
}

Upvotes: 4

Related Questions