Search code examples
phplaravelhttp-status-code-404

Laravel getting 404 error when creating new route


it appears that when I created a new route, I receive the 404 error when trying to access the url, which is funny,. because all of my other routes are working just fine.

My web.php looks like so:

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

The one that is NOT working when I am visiting http://127.0.0.1:8000/alerte is:

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

The controller looks like so:

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

I am banging my head around as I cannot see which is the problem. It is not a live website yet, I am just developing on my Windows 10 pc using WAMP.


Solution

  • Moved my comment to a little bit explained answer.

    So, in your route collection, you have two conflicting routes

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

    and

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

    Imagine that Laravel is reading all routings from top to bottom and it stops to reading next one after the first match.

    In your case, Laravel is thinking that alerte is a username and going to the ProfilesController@index controller. Then it tries to find a user with alerte username and returning 404 because for now, you don't have a user with this username.

    So to fix 404 error and handle /alerte route, you just need to move the corresponding route before /{username} one.

    But here is the dilemma that you got now. What if you will have a user with alerte username? In this case, the user can't see his profile page because now alerte is handling by another route.

    And I'm suggesting to use a bit more friendly URL structure for your project. Like /user/{username} to handle some actions with users and still use /alerte to handle alert routes.