代码之家  ›  专栏  ›  技术社区  ›  Stef-Verniers

Laravel:如何在MVC中正确重写身份验证路由?

  •  1
  • Stef-Verniers  · 技术社区  · 2 年前

    我必须在Laravel为我的预订系统设置身份验证。

    Laravel的基本路由方法和许多教程都是通过在web中编写路由函数来实现的。像这样的php Laraval示例 :

    Route::get('/flights', function () {
        // Only authenticated users may access this route...
    })->middleware('auth');
    

    然而,我被告知这不是设置路由的最佳方式,我应该使用控制器来管理路由。 但这意味着我必须在控制器内设置身份验证方法,老实说,我没有这样做的远见。。 我想我可以这样做( 我的代码 )

    <?php
    
    namespace App\Http\Controllers;
    
    use Illuminate\Http\Request;
    use App\Providers\RouteServiceProvider;
    use Illuminate\Support\Facades\Auth;
    
    class PagesController extends Controller
    {
        public function home() {
            return view('home');
        }
    
        public function reservations() {
            return view('reservations')
            ->middleware(['auth']);
        }
    
        public function newreservations() {
            return view('reservations_new');
        }
    
     }
    

    与此web相结合。php设置:

    Route::get('/reservations.html', [PagesController::class, 'reservations']);
    
    Route::get('/reservations.html/login', [AuthenticatedSessionController::class, 'create']);
    
    Route::post('/reservations.html/login', [AuthenticatedSessionController::class, 'store']);
    
    Route::get('/reservations_new.html', [PagesController::class, 'newReservations']);
    

    但后来我发现了一个错误: 方法Illumbite\View\View::中间件不存在。

    那么,有什么窍门/诀窍/方法可以正确操作吗?

    1 回复  |  直到 2 年前
        1
  •  1
  •   PJB    2 年前

    只要你遵循同样的原则,就没有对错之路。

    我个人这样做:

    Route::middleware('auth')->group(function () {
        // Authenticated routes
    });
    

    您可以检查 this extended discussion

    如果您想在controller中使用中间件, this is the right way

    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');
        }
    }