Laravel 为给出 404 的基本 CRUD 应用程序编辑路由

Laravel edit route for basic CRUD application giving 404

我正在尝试设置一个基本的 Laravel 9 CRUD 应用程序,但我无法让编辑路径为用户控制器工作。

routes/web.php

Route::get('/dashboard', function () { return view('dashboard'); })
    ->middleware(['auth'])->name('dashboard');

use App\Http\Controllers\UserController;

Route::controller(UserController::class)->group(function(){
    Route::get('user','index')->middleware('auth')->name('cases');
    Route::get('user/create','create')->middleware('auth');
    Route::post('user/create','store')->middleware('auth');
    Route::get('user/{$id}/edit','edit')->middleware('auth');
    Route::post('user/{$id}/edit','update')->middleware('auth');
    Route::get('user/{$id}/delete','destroy')->middleware('auth');
    Route::get('user/{id}','show')->middleware('auth');
});

require __DIR__.'/auth.php';

UserController.php

class UserController extends Controller
{
    function edit(int $id)
    {
        echo 123;
    }

我收到 404 NOT FOUND 页面

此外,为什么我看不到此错误的堆栈跟踪?

此外,在某些示例中,我看到有人在控制器方法声明中使用模型 class 名称作为参数类型,例如:

function edit(User $id)
{
    echo 123;
}

但是,我也看到了其他使用 int 的示例。那么哪个是正确的?

首先,在你的 .env 过滤器中你应该把

APP_ENV=local
APP_DEBUG=true

并将您的 web.php 更改为:

<?php

use Illuminate\Support\Facades\Route;

Route::get('/dashboard', function () { return view('dashboard'); })->middleware(['auth'])->name('dashboard');

use App\Http\Controllers\UserController;

Route::controller(UserController::class)->group(function(){
    Route::get('user','index')->middleware('auth')->name('cases');
    Route::get('user/create','create')->middleware('auth');
    Route::post('user/create','store')->middleware('auth');
    Route::get('user/{id}/edit','edit')->middleware('auth');
    Route::post('user/{id}/edit','update')->middleware('auth');
    Route::get('user/{id}/delete','destroy')->middleware('auth');
    Route::get('user/{id}','show')->middleware('auth');
});

require __DIR__.'/auth.php';

然后,尝试运行

php artisan route:list

并检查您的路线是否正确。

并尝试删除用户文件中的中间件,也许您没有登录页面,它会将您重定向到那里。

请确保您的 url 正确 localhost/user/1/edit

路由中的参数不以开头 $。将路线中出现的所有 {$id} 更改为仅 {id}:

Route::controller(UserController::class)->group(function(){
    Route::get('user','index')->middleware('auth')->name('cases');
    Route::get('user/create','create')->middleware('auth');
    Route::post('user/create','store')->middleware('auth');
    Route::get('user/{id}/edit','edit')->middleware('auth');
    Route::post('user/{id}/edit','update')->middleware('auth');
    Route::get('user/{id}/delete','destroy')->middleware('auth');
    Route::get('user/{id}','show')->middleware('auth');
});

更多关于 Route Parameters

编辑:您可能还想看看 Resource ControllersRoute::resource('users', UserController::class); 之类的东西将管理所有必需的路线