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

人气:906 发布:2022-10-16 标签: 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');

我访问http://127.0.0.1:8000/alerte时无法工作的是:

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

控制器如下所示:

namespace AppHttpControllers;

use IlluminateHttpRequest;
use Auth;

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

    public function index(User $user)
    {
        return view('alerte');
    }
}
我在绞尽脑汁,因为我看不出哪一个是问题所在。这还不是一个在线网站,我只是在我的Windows 10 PC上使用WAMP进行开发。

推荐答案

已将我的评论移至稍有解释的答案。

因此,在您的路由集合中,您有两个冲突的路由

Route::get('/{user}', 'ProfilesController@index')->name('profil');

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

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

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

因此,要修复404错误并处理/alerte路由,您只需将对应的路由移到/{username}路由之前。

但这就是你现在面临的两难境地。如果您将拥有一个用户名为alerte的用户,该怎么办?在这种情况下,用户看不到他的个人资料页面,因为现在alerte正在由另一条路线处理。

我建议您的项目使用更友好的URL结构。如/user/{username}处理与用户的某些操作,但仍使用/alerte处理警报路由。

967