1

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

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

where do I put use DB;?
Above your class defenition, in your case above or below use Closure.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.