I have a route with an optional parameter in web.php
:
my web.php
: (the route that has the problem is marked with a comment)
Route::middleware(['auth', 'dashboard'])->group(function () { Route::get('/', 'DashboardController@home')->name('root'); Route::prefix('/drivers')->group(function () { Route::view('/', 'dashboard.driver.main'); Route::post('/', 'UserController@addDriver'); Route::get('/{id}', function ($id) { if (Auth::user()->can('view_user')) { $user = User::find($id); return view('dashboard.user.view', ['user' => $user]); } return view('pages.403'); }); //---------------------------------------- // My route with the problem // --------------------------------------- Route::get('/driver-dropdown/{q?}', function ($q=null){ return $q; })->name('driver.dropdown'); }); });
and it is my dashboard
middleware:
public function handle($request, Closure $next) { if(!in_array(Auth::user()->getOriginal('role'), ['superadmin', 'admin', 'supporter']) ) { return abort(403); } return $next($request); }
When I enter the host-name/drivers/driver-dropdown/jo
URL, I get jo
BUT When I enter the host-name/drivers/driver-dropdown/
URL, I will be redirected to the host-name/
that means root route!
Edit: updated web.php
Advertisement
Answer
You should reorder your routes like this:
Route::get('/driver-dropdown/{q?}', function ($q=null){ return $q; })->name('driver.dropdown'); Route::get('/{id}', function ($id) { if (Auth::user()->can('view_user')) { $user = User::find($id); return view('dashboard.user.view', ['user' => $user]); } return view('pages.403'); });
Currently, when you go to host-name/drivers/driver-dropdown/
, it will match the /{id}
route.