代码之家  ›  专栏  ›  技术社区  ›  sokhib Abdurasulov

为什么Laravel要执行最后一条匹配的路线?

  •  0
  • sokhib Abdurasulov  · 技术社区  · 2 年前

    我刚刚在拉拉威尔开始了一个新项目。我读到Laravel应该走第一条匹配路线,但在这里它要走最后一条匹配路线。如果我删除第三条路线,它将转到第二条路线。为什么会有这种行为?

    use Illuminate\Support\Facades\Route;
    
    Route::get('/', function () {
        return 'Hello, World!';
    });
    Route::get('/', function () {
        return view('welcome');
    });
    Route::get('/', function () {
        return 'Hello, World 2!';
    });
    
    1 回复  |  直到 2 年前
        1
  •  0
  •   Sky    2 年前

    所以你想看的方式就像一本书。它读第1、2和3页。它以3结尾,这意味着它会显示给你那一页。所以它总是显示“你好,世界2”

    所以你想做的是沿着以下几条线来实现它:

    Route::get('/one', function () {
        return 'Hello, World!';
    });
    Route::get('/two', function () {
        return view('welcome');
    });
    Route::get('/three', function () {
        return 'Hello, World 2!';
    });
    

    以下是控制器默认设置的良好参考

    /**
     * Actions Handled By Resource Controller
     * Verb         URI                     Action          Route Name              View
     * GET          /photos                 index           photos.index            index.blade.php
     * POST         /photos                 store           photos.store            (r)edirect to action: 'edit' or 'index' or 'create'
     * GET          /photos/{photo}         show            photos.show             show.blade.php
     * PUT/PATCH    /photos/{photo}         update          photos.update           (r)edirect to action: 'edit' or 'index'
     * DELETE       /photos/{photo}         destroy         photos.destroy          (r)edirect to action: 'index'
    */
    

    最后,你的路线可能如下

    Route::get('/', [WelcomeController::class, 'welcome']);
    

    或者,如果要使用控制器中的所有功能:

    Route::resource('/', WelcomeController::class);
    // Uses all the default resources available (see actions in reference list).
    // Your can also add "->only(['index', 'show']);" to the end or "->exept([]);" the same way