Laravel- Redirecting users with a dynamic parameter through controller

457 Views Asked by At

I have set up the web routing for my url to show as per localhost/testapp/public/{user}/hello

with this current setting

Route::prefix('{user}')->middleware('user')->group(function () {
 Route::prefix('welcome')->group(function () {
  Route::view('/', 'layout.index')->name('index');
  Route::view('thank-you', 'layout.thank-you')->name('thankyou');
 });
 Route::get('/', 'HomeController@redirect');
});

Route::view('/', 'layout.index')->name('index'); this line works fine the way i wanted it to work, however I wasn't able to get the HomeController@redirect to work the way I want it to.

The idea is for the user to be redirected when localhost/testapp/public/{user} is being entered, it would redirect user to the page localhost/testapp/public/{user}/hello

This is how the HomeController looks

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class HomeController extends Controller
{
 public function redirect(Request $request)
 {
  return redirect(['user' => $request, config('settings.default_user')].'/welcome');
 }
}

whereby if the dynamic parameter is somehow not received, I would stick to the default user "admin" that is being stored in my settings.php within the config folder.

1

There are 1 best solutions below

0
On

Use an optional parameter in the routes file, otherwise it will show a 404 if no {user} is provided

Route::prefix('/{user?}')

Then with this in config/settings.php

<?php
return ['default_user' => 456];

And this in the HomeController

public function redirect(Request $request)
{
    if (empty($request->user)) {
        return redirect(config('settings.default_user') . '/welcome');
    } else {
        return redirect($request->user . '/welcome');
    }
}

Now when I try in my browser

  • /123 redirects me to /123/welcome.
  • / redirects me to 456/welcome.