phplaravelrouteslaravel-7

How to use str_replace in Laravel Dynamic route


I want to create a dynamic url from my title in laravel routes.

I tried to use such as :

Route::get('/page/{strtolower(str_replace(" ", "-", $bank->bank_name))}', 'BankController@show');

But this code gives me 404 error. I tried to google but unable to find anything useful.

ANyone who could help?


Solution

  • Your route should look like this:

    Route::get('/page/{BankName}', 'BankController@show');
    

    Inside your controller show function:

    public function show($BankName){
        $BankName = strtolower(str_replace(" ", "-", $BankName));
    }
    

    To check if it works in Routes, you can try:

    Route::get('/Page/{BankName}', function ($BankName){
        echo strtolower(str_replace(" ", "-", $BankName));
    });