Ad

Use Custom Middleware In Controller

- 1 answer

I created middleware: php artisan make:middleware CheckUserStatus

In this middleware I have:

namespace App\Http\Middleware;

use Closure;

class CheckUserStatus
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if(Auth()->check() AND Auth()->user()->status === 0) { // user is logged in but it is blocked
            auth()->logout();
            return redirect('/');
        }

        return $next($request);
    }
}

Then, one of my controller I have:

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Middleware\CheckUserStatus;


class productsController extends Controller
{
    public function __construct () {
        $this->middleware('auth');
        $this->middleware('CheckUserStatus');
    }
}

This gives ReflectionException - Class CheckUserStatus does not exist

What I'm doing wrong ?

Ad

Answer

You need to register your middleware if you want to reference it by a string key. Check out the docs here.

Alternatively, you could use the fully qualified class name: try CheckUserStatus::class instead of 'CheckUserStatus'.

Ad
source: stackoverflow.com
Ad