Class 'App\Http\Middleware\DB' 在 Laravel 5 中使用中间件时未找到
Class 'App\Http\Middleware\DB' not found when using Middleware in Laravel 5
所以我想检查数据库是否已连接 laravel 5.I 为此使用了中间件。
中间件代码
Middleware.php
命名空间App\Http\Middleware;
use Closure;
class MyMiddleware {
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if(DB::connection()->getDatabaseName())
{
echo "conncted sucessfully to database ".DB::connection()->getDatabaseName();
}else{
die("Couldn't connect");
}
return $next($request);
}
}
将其添加到 kernel.php
protected $routeMiddleware = [
'error' => 'App\Http\Middleware\MyMiddleware',
'auth' => 'App\Http\Middleware\Authenticate',
'auth.basic' => 'Illuminate\Auth\Middleware\AuthenticateWithBasicAuth',
'guest' => 'App\Http\Middleware\RedirectIfAuthenticated',
];
我想检查特定路线是否有错误
Route::get('/wow', ['middleware' => 'error', function () {
//
}]);
对于中间件来说一切正常,但没有 类 或 laravel 核心功能,例如检查数据库 working.How 我能解决吗?
这是 laravel 显示的错误
FatalErrorException in MyMiddleware.php line 18:
Class 'App\Http\Middleware\DB' not found
您正在命名空间 App\Http\Middleware
中工作。因此,除非您另有指定,否则它会在该命名空间中搜索数据库。
任意设置
use DB;
或将数据库用作
\DB::connection()->...
有关命名空间的更多信息:http://php.net/manual/en/language.namespaces.php
所以我想检查数据库是否已连接 laravel 5.I 为此使用了中间件。
中间件代码
Middleware.php
命名空间App\Http\Middleware;
use Closure;
class MyMiddleware {
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if(DB::connection()->getDatabaseName())
{
echo "conncted sucessfully to database ".DB::connection()->getDatabaseName();
}else{
die("Couldn't connect");
}
return $next($request);
}
}
将其添加到 kernel.php
protected $routeMiddleware = [
'error' => 'App\Http\Middleware\MyMiddleware',
'auth' => 'App\Http\Middleware\Authenticate',
'auth.basic' => 'Illuminate\Auth\Middleware\AuthenticateWithBasicAuth',
'guest' => 'App\Http\Middleware\RedirectIfAuthenticated',
];
我想检查特定路线是否有错误
Route::get('/wow', ['middleware' => 'error', function () {
//
}]);
对于中间件来说一切正常,但没有 类 或 laravel 核心功能,例如检查数据库 working.How 我能解决吗?
这是 laravel 显示的错误
FatalErrorException in MyMiddleware.php line 18:
Class 'App\Http\Middleware\DB' not found
您正在命名空间 App\Http\Middleware
中工作。因此,除非您另有指定,否则它会在该命名空间中搜索数据库。
任意设置
use DB;
或将数据库用作
\DB::connection()->...
有关命名空间的更多信息:http://php.net/manual/en/language.namespaces.php