Laravel Middleware return variable to controller
I believe the correct way to do this (in Laravel 5.x) is to add your custom fields to the attributes property.
From the source code comments, we can see attributes is used for custom parameters:
/**
* Custom parameters.
*
* @var \Symfony\Component\HttpFoundation\ParameterBag
*
* @api
*/
public $attributes;
So you would implement this as follows;
$request->attributes->add(['myAttribute' => 'myValue']);
You can then retrieved the attribute by calling:
\Request::get('myAttribute');
Or from request object in laravel 5.5+
$request->get('myAttribute');
In Laravel >= 5 you can use $request->merge
in the middleware.
public function handle($request, Closure $next)
{
$request->merge(["myVar" => "1234"]);
return $next($request);
}
And in the controller
public function index(Request $request)
{
$myVar = $request->myVar;
...
}
Instead of custom request parameters, you can follow the inversion-of-control pattern and use dependency injection.
In your middleware, register your Page
instance:
app()->instance(Page::class, $page);
Then declare that your controller needs a Page
instance:
class PagesController
{
protected $page;
function __construct(Page $page)
{
$this->page = $page;
}
}
Laravel will automatically resolve the dependency and instantiate your controller with the Page
instance that you bound in your middleware.