所以我想检查数据库是否在laravel 5中连接。我使用了Middlewares。
中间件代码
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 () {
//
}]);
对于中间件来说,每件事情都运行良好,但是没有像check db这样的类或laravel核心函数正在工作。我该如何解决它?
这是laravel显示的错误
FatalErrorException in MyMiddleware.php line 18:
Class 'App\Http\Middleware\DB' not found
答案 0 :(得分:2)
您正在使用名称空间App\Http\Middleware
。因此,它会在该命名空间中搜索DB,除非您另行指定。
设置
use DB;
或者将数据库用作
\DB::connection()->...
有关命名空间的更多信息:http://php.net/manual/en/language.namespaces.php