Search code examples
laravelrouteslaravel-routing

Laravel go-back dynamic button?


I want to implement a dynamic way of the go-back button in my Laravel project.

So I have this button:

<a href="WHAT TO DO HERE">
    <div class="go-back">
        <div class="go-back-inside">
            <h6 class="text">Go Back</h6>
        </div>
    </div>
</a>

Which I have included on every page, what I want to do is to have one button that is included in all pages, and for instance, if I am on bentley-flying-spur and click on back I want to go to the prefix's base route (/) [services/cars/], or if I am on riva and click on the go-back-button to go to the base route (/) [services/yacht/];

The same button is included in both bentley-flying-spur and riva how can it dynamically go to the route group's (/)

Route::prefix('services')->group(function () {

    Route::get('/', function () {
        return view('web.services');
    });
    Route::prefix('cars')->group(function () {
        Route::get('/', function () {
            return view('web.modules.cars.products');
        });
        Route::get('/bentley-flying-spur', function () {
            return view('web.modules.cars.models.bentley-flying-spur');
        });
    });
    Route::prefix('yacht')->group(function () {
        Route::get('/', function () {
            return view('web.modules.riva.products');
        });
        Route::get('/riva', function () {
            return view('web.modules.riva.models.riva');
        });
    });
}):

DYNAMIC ROUTES

Route::get('/', 'MainController@index');
Route::get('/services', 'MainController@services');
Route::get('/services/{service}', 'MainController@service');
Route::get('/services/{service}/{product}', 'MainController@product');

Solution

  • Use {{url(request()->route()->getPrefix())}} in your href attribute.

    What I would do is move the null routes out to the next prefix like below. I tested and it should work.

    Route::prefix('services')->group(function () {
    
        Route::get('/', function () {
            return view('web.services');
        });
    
        Route::get('/cars', function () {
            return view('web.modules.cars.products');
        });
    
        Route::get('/yacht', function () {
            return view('web.modules.riva.products');
        });
    
        Route::prefix('cars')->group(function () {
            Route::get('/bentley-flying-spur', function () {
                return view('web.modules.cars.models.bentley-flying-spur');
            });
        });
    
        Route::prefix('yacht')->group(function () {
            Route::get('/riva', function () {
                return view('web.modules.riva.models.riva');
            });
        });
    });
    

    Which I kind of think it cleans it up as well and is a little bit clearer.