Reputation: 1273
So I want to check whether the database is connected in laravel 5.I used Middlewares for this.
Middleware code
Middleware.php
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);
}
}
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 () {
//
}]);
Every thing works fine for the middleware but no classes or laravel core functions like check db is working.How do I solve it?
This is the error laravel shows
FatalErrorException in MyMiddleware.php line 18:
Class 'App\Http\Middleware\DB' not found
Upvotes: 1
Views: 5331
Reputation: 5963
You're working in namespace App\Http\Middleware
. So it searches for DB in that namespace unless you specify otherwise.
Either set
use DB;
Or use the DB as
\DB::connection()->...
More info on namespaces: http://php.net/manual/en/language.namespaces.php
Upvotes: 2