Skip to content
Advertisement

Best way to obtain prefix and last part of url in Laravel

I have a group route like this

PHP LARAVEL 9

/**
 * ACCOMODATIONS
 */
Route::controller(AccomodationsController::class)->group(function () {

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

            Route::GET('/', 'index');

            Route::GET('/italy', 'index');
    
            Route::GET('/greece', 'index');

        });

});

In the controller side I want to obtain the accomodations part and the italy greece part without slashes. I’m doing like this

PHP LARAVEL 9

class AccomodationsController extends Controller
{

    public function index(request $request){

        $listType = [
            'type' => trim($request->route()->getPrefix(), '/'),
            'route' => request()->segment(count(request()->segments()))
        ];

     dd($listType);
    
    );
}

/*
http://example.com/accomodations outputs
array [
  "type" => "accomodations"
  "route" => ""
]
/*

/*
http://example.com/accomodations/italy outputs
array [
  "type" => "accomodations"
  "route" => "italy"
]
*/

/*
http://example.com/accomodations/greece outputs
array [
  "type" => "accomodations"
  "route" => "greece"
]
*/

This works but the way I’m manipulating the request in $listType seems a little bloated to me, is there a cleaner way in laravel?

Advertisement

Answer

Use parameterized route for same method.

Routes

Route::controller(AccomodationsController::class)->group(function () {
    Route::prefix('accomodations')->group(function () {
        Route::GET('/{destination}', 'index');
    });
});

Controller

public function index(Request $request, $destination){
    $listType = [
        'type' => trim($request->route()->getPrefix(), '/'),
        'route' => $destination
    ];
    dd($listType);
);

If your destination is optional you can use optional parameter

Edit 1:

Route with Optional Parameter

Route::controller(AccomodationsController::class)->group(function () {
    Route::prefix('accomodations')->group(function () {
        Route::GET('/{destination?}', 'index');
    });
});

Controller with Optional parameter

public function index(Request $request, $destination=''){
    $listType = [
        'type' => trim($request->route()->getPrefix(), '/'),
        'route' => $destination
    ];
    dd($listType);
);

you can assign any value (null, string, int, etc.) to the destination variable just like the default function argument in PHP.

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