Skip to content
Advertisement

laravel – how to add prefix in all url without affecting route existing

i have url like this mysite.com/company, i want add prefix to url to become mysite.com/home/company.

I’ve tried to add a route group, but that requires me to update all existing routes.

can i add a prefix in all url without affecting the existing route ?

i used laravel 5.6

Advertisement

Answer

I have created a sandbox so that you can view and play around with the code used for this answer.

I know the sandbox uses a different Laravel version (version 7), but looking at the documentation for version 5.6 the routing does not seem to be that much different than that of version 7.

What you can do is wrap the already existing routes inside an anonymous function and assign it to a variable, you can then use this variable and pass it as a parameter to the group routing function along with a prefix, e.g.

$routes = function() {
    Route::get('company', function () {
        return 'companies';
    });

    Route::get('company/{company}', function ($company) {
        return "company $company";
    });

    Route::delete('company/{company}', function ($company) {
        return "deleting company $company...";
    });

    Route::get('company/{company}/staff', function ($company) {
        return "staff list for company $company...";
    });
};

Route::prefix('/')->group($routes);
Route::prefix('/home')->group($routes);

When running php artisan route:list the following is returned:

+--------+----------+------------------------------+------+---------+------------+
| Domain | Method   | URI                          | Name | Action  | Middleware |
+--------+----------+------------------------------+------+---------+------------+
|        | GET|HEAD | api/user                     |      | Closure | api        |
|        |          |                              |      |         | auth:api   |
|        | GET|HEAD | company                      |      | Closure | web        |
|        | GET|HEAD | company/{company}            |      | Closure | web        |
|        | DELETE   | company/{company}            |      | Closure | web        |
|        | GET|HEAD | company/{company}/staff      |      | Closure | web        |
|        | GET|HEAD | home/company                 |      | Closure | web        |
|        | GET|HEAD | home/company/{company}       |      | Closure | web        |
|        | DELETE   | home/company/{company}       |      | Closure | web        |
|        | GET|HEAD | home/company/{company}/staff |      | Closure | web        |
+--------+----------+------------------------------+------+---------+------------+

You can see above that the routes can now be accessed via both / and home/, e.g. http://example.com/company and http://example.com/home/company without the need for duplicating routes.

If you need to add any more prefixes in the future you just simply add a new Route::prefix("<prefix>")->group($routes); to the routes file.


The update below is in response to the comment provided by OP.

To get this correct you are looking for a way to automatically convert all instances of the url function from url('someurl') to url('home/someurl'), e.g.

  • url('company') will become url('home/company')
  • url('knowledgebase') will become url('home/knowledgebase')

If so then I have two solutions for you:

  1. Can you not simply do a search and replace within the IDE you are using?

  2. You can override Laravel’s url helper function to prefix all path’s with home/, to do so you can do the following:

I have created another sandbox so that you can view and play around with the code used for this answer.

First create a helpers.php file anywhere within your Laravel application, when testing this code I placed the file in the root directory of the application, e.g. /var/www/html/helpers.php.

Second you need to override the url helper function, to make sure you don’t lose any functionality I grabbed the original source code of the function from Laravel’s github repository. I then modified it to include the prefix, so place the following in the new helpers.php file:

<?php

use IlluminateContractsRoutingUrlGenerator;

if (! function_exists('url')) {
    /**
     * Generate a url for the application.
     *
     * @param  string|null  $path
     * @param  mixed  $parameters
     * @param  bool|null  $secure
     * @return IlluminateContractsRoutingUrlGenerator|string
     */
    function url($path = null, $parameters = [], $secure = null)
    {
        if (is_null($path)) {
            return app(UrlGenerator::class);
        }

        $path = "home/$path";

        return app(UrlGenerator::class)->to($path, $parameters, $secure);
    }
}

Next, you need to load your helpers.php file before Laravel loads their helper functions, otherwise it wont load, to do so add require __DIR__.'/../helpers.php'; to public/index.php before require __DIR__.'/../vendor/autoload.php';, e.g.

require __DIR__.'/../helpers.php';
require __DIR__.'/../vendor/autoload.php';

Now you can use the new url function within your application, I have given some examples in the web.php routes file:

<?php

use IlluminateSupportFacadesRoute;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/', function () {
    echo url("company");

    echo "<br/>";

    echo url("knowledgebase");
});

The above will output to the webpage:

http://example.com/home/company
http://example.com/home/knowledgebase

Now if you need to change the url function slightly to more fit your requirements you can do so by modifying it within the helpers.php file.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement