Application \ Http \ Middleware \ DB class not found when using middleware in Laravel 5

So, I want to check if the database is connected in laravel 5. I used Middlewares for this.

Intermediate 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 specific route

 Route::get('/wow', ['middleware' => 'error', function () { // }]); 

Every thing is great for middleware, but no classes or basic laravel functions like check db work. How to solve this?

This laravel error shows

 FatalErrorException in MyMiddleware.php line 18: Class 'App\Http\Middleware\DB' not found 
+1
source share
1 answer

You work in the App\Http\Middleware namespace. Therefore, it searches for a database in this namespace, unless you specify otherwise.

Or install

 use DB; 

Or use DB as

 \DB::connection()->... 

Additional information about namespaces: http://php.net/manual/en/language.namespaces.php

+2
source

All Articles