1
votes

Currently I am working with a new project with laravel. For this project I need to add prefix for a group of routes and need to add the prefix by using middleware. The middleware is -

public function handle($request, Closure $next)
    {

        $segments = $request->segments();

        if( $request->is('admin/*') ){
            return $next($request);
        }
        array_unshift($segments,'admin');
        return redirect()->to(implode('/',$segments));
    }


And my routes/web.php file is-

Route::group(['middleware' => 'admin','prefix' => 'admin'],function(){
    Route::get('segments',function(){
       return request()->segments();
    });
});


But unfortunately this is not working for me. The middleware not force redirect me if I don't add admin/ prefix manually. But if I remove 'prefix' => 'admin' from the route group then it works. How can I solve this problem?
Sorry, for my bad English.

1
Route::get('/segments') Add / before get requestManiruzzaman Akash
Not working. :( @ManiruzzamanAkashSajeeb
What's the use case for this? It seems like you are trying to redirect user away when user is in admin/* route? Perhaps we can give you a better answer if you can describe what's the purpose of this code?Lionel Chan
My purpose is if we hit a route domain.com/segments then it redirects to domain.com/admin/segments and the route also allow the /admin prefix. @LionelChanSajeeb

1 Answers

0
votes

This approach will not work for you because you're only applying the middleware to the admin/* routes.

If you want to redirect a user from any not admin/* routes to admin ones, you could do something like this instead. Add this route to the end of the web.php:

Route::get('{param1?}/{param2?}/{param3?}', 'RedirectController@redirectoToAdmin');

Create RedirectController controller and do this:

public function redirectoToAdmin()
{
    return redirect('admin/' . request()->path());
}

Also, remove the admin middleware from the route group you've shown.