【问题标题】:How to use "OR" in route parameter?如何在路由参数中使用“OR”?
【发布时间】:2019-08-18 04:44:18
【问题描述】:

我正在构建一个类似于 twitter 的网站,但我遇到了路由问题:

  1. 此代码会将用户带到具有给定 id 的人员的个人资料页面。

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

  1. 此代码会将用户带到具有给定用户名的人的个人资料页面。

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

  1. 最后,此代码会将用户带到具有给定电子邮件的人的个人资料页面。

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

我的意思是所有这三个 URL 都会向用户显示相同的页面:

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

我的问题是: 有没有办法合并所有这些路线?如下:

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

【问题讨论】:

    标签: laravel laravel-routing


    【解决方案1】:

    不确定合并路线,但您可以这样编写路线

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

    然后将ProfileControllershow 的方法签名更改为类似这样

    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
    }
    

    这里有一个link,这是一个很好的方法来检查一个值是否是有效的电子邮件地址

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-12-01
      • 2020-12-05
      • 1970-01-01
      • 2011-10-04
      • 2017-10-07
      • 1970-01-01
      • 2016-09-09
      • 2019-01-30
      相关资源
      最近更新 更多