I have Created a new middleware for checking the user token I have create middleware then adeded to kernal.php and but when i tried to access $request in middleware i am getting the error
Here is my is my middleware code
namespace App\Http\Middleware;
use Illuminate\Http\Request;
use Closure;
use App\User;
class CheckToken
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if($request->header('Token') == '123')
{
return ['status' =>2, 'msg' => 'Unathorized'];
}
else
{
return $next($request);
}
}
}
Here is my kernal file
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
'verifyToken' => \App\Http\Middleware\CheckToken::class,
];
and I am getting this error
Argument 1 passed to Illuminate\Routing\Middleware\ThrottleRequests::addHeaders() must be an instance of Symfony\Component\HttpFoundation\Response, instance of Illuminate\Http\Request given, called in C:\xampp\htdocs\idoltime\vendor\laravel\framework\src\Illuminate\Routing\Middleware\ThrottleRequests.php on line 62
You may use
// return $request;
if($request->header('Token') == '123')
{
$response = [
'status' => 2,
'message' => 'Unauthorized',
];
return response()->json($response, 413);
}
else
{
return $next($request);
}
I face the same problem but not find any answer on the internet. Here is the solution to how I solved this issue.
Step 1: Create a separate route for example
Route::get('header_token', function() {
return response()->json(['status' =>2, 'msg' => 'Unathorized']);
})->name('header_token');
Step 2: Redirect to header_token route
keep in mind you can not return data as response, so return to a route that will return your data
public function handle($request, Closure $next)
{
if($request->header('Token') == '123')
{
return redirect(route('header_token'));
}
else
{
return $next($request);
}
}
if (auth()->user()) {
return $next($request);
}else{
return JsonResponse::respondError("you are not active email");
}
I solved this problem like this
exit(response()->json( json_encode(['message' => 'Text']), 403) );
echo() - var_dump() - print() - print_r() - also works too...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.