Laravel 创建新路由时出现 404 错误

FBK*_*FBK 1 php http-status-code-404 laravel

看起来,当我创建新路由时,尝试访问 url 时收到 404 错误,这很有趣。因为我的所有其他路线都运行良好。

我的 web.php 看起来像这样:

Auth::routes();

Route::post('follow/{user}', 'FollowsController@store');

Route::get('/acasa', 'HomeController@index')->name('acasa');
Route::get('/{user}', 'ProfilesController@index')->name('profil');
Route::get('/profil/{user}/edit', 'ProfilesController@edit')->name('editareprofil');
Route::patch('/profil/{user}', 'ProfilesController@update')->name('updateprofil');

Route::get('/alerte', 'PaginaAlerte@index')->name('alerte');
Route::get('/alerte/url/{user}', 'UrlsController@index')->name('editurl');
Route::post('/alerte/url/{user}', 'UrlsController@store')->name('updateurl');
Route::get('/alerte/url/{del_id}/delete','UrlsController@destroy')->name('deleteurl');
Run Code Online (Sandbox Code Playgroud)

当我访问http://127.0.0.1:8000/alerte时不起作用的是:

Route::get('/alerte', 'PaginaAlerte@index')->name('alerte');
Run Code Online (Sandbox Code Playgroud)

控制器看起来像这样:

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Auth;

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

    public function index(User $user)
    {
        return view('alerte');
    }
}
Run Code Online (Sandbox Code Playgroud)

我正在摇头,因为我看不出问题所在。这还不是一个实时网站,我只是在我的 Windows 10 电脑上使用 WAMP 进行开发。

ale*_*kov 7

将我的评论移至稍微解释一下的答案。

因此,在您的路线集合中,您有两条相互冲突的路线

Route::get('/{user}', 'ProfilesController@index')->name('profil');
Run Code Online (Sandbox Code Playgroud)

Route::get('/alerte', 'PaginaAlerte@index')->name('alerte');

Run Code Online (Sandbox Code Playgroud)

想象一下 Laravel 正在从上到下读取所有路由,并在第一个匹配后停止读取下一个路由。

在你的例子中,Laravel 认为这alerte是一个用户名并转到控制器ProfilesController@index。然后它尝试查找具有alerte用户名的用户并返回 404,因为目前您还没有具有该用户名的用户。

因此,要修复 404 错误并处理/alerte路由,只需将相应的路由移至前/{username}一个即可。

但这就是你现在面临的困境。如果您有一个带有alerte用户名的用户怎么办?在这种情况下,用户无法看到他的个人资料页面,因为现在alerte正在通过另一条路线进行处理。

我建议为您的项目使用更友好的 URL 结构。喜欢/user/{username}与用户一起处理一些操作,并且仍然用于/alerte处理警报路由。