post-image

[Bài đọc] Đăng ký Middlware cho Controller

Laravel cơ bản

Chúng ta có thể đăng ký middlware cho controller trong file routes, chẳng hạn như:

Route::get('profile', '[email protected]')->middleware('auth');

Ngoài ra, chúng ta cũng có thể đăng ký middleware ở bên trong constructor của controller, chẳng hạn như:

class UserController extends Controller
{
    /**
     * Instantiate a new controller instance.
     *
     * @return void
     */
     public function __construct()
     {
        $this->middleware('auth');

        $this->middleware('log')->only('index');

        $this->middleware('subscribed')->except('store');
     }
}

Hoặc, thậm chí chúng ta cũng có thể định nghĩa middlware ngay bên trong constructor của controller thông qua một Closure. Chẳng hạn như:

$this->middleware(function ($request, $next) {
    // ...

    return $next($request);
});

Leave a Reply

Your email address will not be published.