0

I'm building a twitter-ish website and I'm having a problem with routing:

  1. this code will bring the user to the profile page of the person with the given id.

Route::get('/profile/{id}', 'ProfileController@show')->name('profile.show');

  1. this code will bring the user to the profile page of the person with the given username.

Route::get('/profile/{username}', 'ProfileController@show')->name('profile.show');

  1. and finally, this code will bring the user to the profile page of the person with the given email.

Route::get('/profile/{email}', 'ProfileController@show')->name('profile.show');

I mean all these three URLs will show the user the same page:

example.com/profile/1 example.com/profile/rahimi0151 example.com/profile/rahimi0151@gmail.com

my question is: is there a way to merge all these routes? like below:

Route::get('/profile/{id|username|email}', 'ProfileController@show')->name('profile.show');

Rahimi0151
  • 395
  • 3
  • 11

1 Answers1

1

Am not sure about merging the routes but you could write your route like this

Route::get('/profile/{identifier}', 'ProfileController@show')->name('profile.show');

and then change the method signature for show in ProfileController to something like this

public function show($identifier) {
    if (is_numeric($identifier)) {
        // do something
    } else if ($this->isEmail($identifier)) {
        // do something
    } else {
        // assume it is a username, and do something with that
    }
}

// method to check if value provided is an email
// preferably, move this to a file of your custom helper functions
private function isEmail($value) {
    // check if value is an email 
    // and return true/false indicating whether value is an email
}

And here is a link for a good way on how to check if a value is valid email address

kellymandem
  • 1,709
  • 3
  • 17
  • 27