ReflectionException - Laravel 5.2 中不存在中间件类
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37568881/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ReflectionException - Middleware class does not exist Laravel 5.2
提问by Devendra Verma
I am building an API with stateless HTTP basic authentication in Laravel 5.2, as per documentation Stateless HTTP Basic Authentication , I have created following Middleware
我正在 Laravel 5.2 中使用无状态 HTTP 基本身份验证构建 API,根据文档无状态 HTTP 基本身份验证,我创建了以下中间件
app/Http/Middleware/AuthenticateOnceWithBasicAuth.php
应用程序/Http/中间件/AuthenticateOnceWithBasicAuth.php
<?php
namespace Illuminate\Auth\Middleware;
use Auth;
use Closure;
class AuthenticateOnceWithBasicAuth
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
return Auth::onceBasic() ?: $next($request);
}
}
And then registered it in Kernel.php
然后在Kernel.php中注册
app/Http/kernel.php
应用程序/Http/kernel.php
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'can' => \Illuminate\Foundation\Http\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'auth.basic.once' => \App\Http\Middleware\AuthenticateOnceWithBasicAuth::class,
];
I am using it in route as follows
我在路线中使用它如下
Route::group(['prefix' => 'admin', 'middleware' => 'auth.basic.once'], function () {
Route::get('service/create', function () {
return response()->json(['name' => 'Abigail', 'state' => 'CA'], 200);
});
});
But it is giving me
但它给了我
ReflectionException in Container.php line 734: Class App\Http\Middleware\AuthenticateOnceWithBasicAuth does not exist
Container.php 第 734 行中的 ReflectionException:Class App\Http\Middleware\AuthenticateOnceWithBasicAuth 不存在
I have run following commands but with no success
我已经运行了以下命令但没有成功
composer dump-autoload
php artisan clear-compiled
php artisan optimize
Any help would be much appreciated. Thanks in advance.
任何帮助将非常感激。提前致谢。
回答by Filip Koblański
Well first of all look at the namespaces:
首先看一下命名空间:
namespace Illuminate\Auth\Middleware;
you should rename it to:
您应该将其重命名为:
namespace App\Http\Middleware;
in the middleware you need to do something like this:
在中间件中,您需要执行以下操作:
public function handle($request, Closure $next) {
if (!Auth::onceBasic()) {
if ($request->ajax() || $request->wantsJson()) {
return response('Unauthorized.', 401);
} else {
return redirect()->guest('login');
}
}
return $next($request);
}