问题描述
所以我想检查数据库是否连接在laravel 5.我使用Middlewares为此。
So I want to check whether the database is connected in laravel 5.I used Middlewares for this.
中间件代码
Middleware.php
Middleware.php
命名空间App\Http \Middleware;
namespace 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
added it to 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',
];
,我想检查特定路线是否有错误
and I want to check if there is an error in a particular route
Route::get('/wow', ['middleware' => 'error', function () {
//
}]);
每一件事都适用于中间件,但是没有类或者laravel核心函数,如check db是工作的。我要解决吗?
Every thing works fine for the middleware but no classes or laravel core functions like check db is working.How do I solve it?
这是错误laravel显示
This is the error laravel shows
FatalErrorException in MyMiddleware.php line 18:
Class 'App\Http\Middleware\DB' not found
推荐答案
您正在名称空间 App\Http \Middleware
中工作。
You're working in namespace App\Http\Middleware
. So it searches for DB in that namespace unless you specify otherwise.
要么设置
use DB;
或使用DB作为
\DB::connection()->...
有关命名空间的详细信息:
More info on namespaces: http://php.net/manual/en/language.namespaces.php
这篇关于在Laravel 5中使用中间件时未找到类'App\Http \Middleware\DB'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!