i added header in middleware and i want to check in my controller that header that i set exists or not . the problem i cant watch headers in controller debugging? how can i do that? anyway use case for this is cors problem
this is my middleware:
public function handle(Request $request, Closure $next)
{
return $next($request)
->header('Access-Control-Allow-Origin', '*');
}
and this is my controller:
public function action()
{
dd(request()->headers->get("Access-Control-Allow-Origin")); //always null
}
You need to call the set method:
public function handle(Request $request, Closure $next)
{
$request->headers->set('Access-Control-Allow-Origin', '*');
return $next($request);
}
Then you can retrieve the header:
public function action()
{
dd(request()->headers->get("Access-Control-Allow-Origin")); // *
}
Related
I have a middleware in my project that call in every request. It will check if Request has a specific cookie, then delete another cookie. But it seems Cookies are not forgotten or set in Laravel until return in the response. something like
return response('view')->withCookie($cookie); that is not possible in middlewares.
Also I tried Cookie::queue(Cookie::forget('myCookie')); nothing happened and cookie is shown in my browser.
This is my middleware handle method:
public function handle(Request $request, Closure $next)
{
if (! $request->cookie('clear_token')) {
cookie()->forget('access_token'); # not worked
Cookie::queue(Cookie::forget('access_token')); # not worked
}
return $next($request);
}
You can change the response in middleware too:
https://laravel.com/docs/5.0/middleware
<?php namespace App\Http\Middleware;
class AfterMiddleware implements Middleware {
public function handle(\Illuminate\Http\Request $request, \Closure $next)
{
$response = $next($request);
// Forget cookie
return $response;
}
}
I am trying to send a variable to terminate of middleware from route:
Route::group(['middleware' => 'checkUserLevel'], function () {
// my routes
});
I can get checkUserLevel in handle of middleware but I need to access in terminate method too, what should I do?
public function handle($request, Closure $next, $key)
{
dd($key); // it returns variable
}
public function terminate($request, $response)
{
//I need that variable here
}
As mentioned in documentation, if you would like to use the same instance of middleware (because by default it is using the fresh instance of middleware) you need to register the middleware as singleton.
You can register it as singleton by adding to your ServiceProvider's register method
public function register()
{
$this->app->singleton(\App\Http\Middleware\YourMiddleware::class);
}
Then you can use the class' property like the first example of lorent's answer
protected $foo;
public function handle($request, Closure $next)
{
$this->foo = 'bar';
return $next($request);
}
public function terminate($request, $response)
{
// because we cannot use `dd` here, so the example is using `logger`
logger($this->foo);
}
You can do:
protected $key;
public function handle($request, Closure $next, $key)
{
$this->key = $key;
}
public function terminate($request, $response)
{
$this->key; //access property key
}
even though this should be passed via request global. Like:
public function handle($request, Closure $next)
{
$request->input('key');
}
public function terminate($request, $response)
{
$request->input('key');
}
Edited:
Route::group(['middleware' => 'checkUserLevel'], function () {
Route::get('/test/{testparam}', function () {
});
});
public function handle($request, Closure $next)
{
$request->route('testparam');
}
public function terminate($request, $response)
{
$request->route('testparam');
}
I know this is ages old, but you could also use a static property. That saves you from having to register a singleton:
<?php
namespace App\Http\Middleware;
class MyMiddleware {
private static $key;
public function handle($request, Closure $next, $key)
{
self::$key = ($key); // it returns variable
}
public function terminate($request, $response)
{
$key = self::$key;
}
}
This works in my Laravel 5.8 application, don't see why it wouldnt' work anywhere else. Cannot say if there's any reason NOT to do this, but I don't know of one.
I'm using this myself to generate a Cache key in my handle function, and reuse the same key in my terminate function.
I want to use a terminable middleware for request logging:
<?php
namespace Illuminate\Session\Middleware;
use Closure;
use App\Helpers\Logger;
class LogRequest
{
public function handle($request, Closure $next)
{
return $next($request);
}
public function terminate($request, $response)
{
Logger::log($request, $response, $additionalInfo)
}
}
How can I pass the $additionalInfo from the controller to the middleware?
EDIT:
Unfortunately the additional info is generated in the controller. I therefore cannot hard code it in the route middleware function
Have you try to add to kernel.php:
protected $routeMiddleware = [
......
'LogRequest'=> \App\Http\Middleware\LogRequest::class
];
in the LogRequestMiddleware:
public function handle($request, Closure $next, $additionalInfo)
{
//here you have $additionalInfo
$request->attributes->add(["info" => $additionalInfo]);
return $next($request);
}
public function terminate($request, $response)
{
dd( $request->attributes);
}
And in controller:
public function __construct()
{
$additionalInfo = "test"
$this->middleware("LogRequest:$additionalInfo");
}
I think you can set some attribute to the request object in your controller while handling it, and the request object itself will be passed to terminate($request, $response) as the first parameter. Then you can extract whatever you set in your controller and use it.
Edited: You might be able to do this
Controller
$request->attributes->add(['additionalInfo' => 'additionalInfoValue']);
Middleware
public function terminate($request, $response)
{
$additionalInfo = $request->attributes('additionalInfo' => $additionalInfo);
Logger::log($request, $response, $additionalInfo)
}
this my middleware:
<?php
namespace App\Http\Middleware;
use Closure;
class CheckSession
{
public function handle($request, Closure $next)
{
return $next($request);
}
public function CheckSessionPageReuestTokenFailed($request, $next)
{
if ($request->session()->has('request_failed')) {
return $next($request);
} else {
echo 'forbidden';
}
}
}
how i can use method CheckSessionPageReuestTokenFailed($request, $next)?
thanks
Why you have written this method ?. you can write this code into handle method.
public function handle($request, Closure $next)
{
if ($request->session()->has('request_failed')) {
return $next($request);
} else {
echo 'forbidden';
}
}
and also you need register this middleware into $routeMiddleware array in
app/Http/Kernel.php file.
add this line:
'CheckSession' => CheckSession::class,
read laravel documentation to know more https://laravel.com/docs/5.4/middleware
public function handle($request, Closure $next)
{
$this->CheckSessionPageReuestTokenFailed($request, $next);
return $next($request);
}
You can use inside handle() method.
public function handle($request, Closure $next)
{
$this->CheckSessionPageReuestTokenFailed($request, $next);
return $next($request);
}
I'm trying to change the header of my request before passing it to the controller using a middleware but it seems $next($request) executes the code in my controller. Is there a way to change the header then send the updated request to my controller?
My middleware:
class JWTAuthenticator
{
public function handle($request, Closure $next)
{
$token =JWTAuth::getToken();
$my_new_token = JWTAuth::refresh($token);
//it runs here
$response = $next($request);
//it runs this part after executing the controller
$response->header('Authorization','Bearer '.$my_new_token);
return $response;
}
This is how the middleware is assigned to my route:
Route::get('/{user}', 'v1\UserController#find')->middleware('jwt_auth');
That way you are excecuting the $response->header('Authorization','Bearer '.$my_new_token); sentence after the request was attended.
Change your code as follows:
class JWTAuthenticator
{
public function handle($request, Closure $next)
{
$token =JWTAuth::getToken();
$my_new_token = JWTAuth::refresh($token);
$request->headers->set('Authorization','Bearer '.$my_new_token);
return $next($request);
}