Routes in Laravel with or without a forward slash?

风格不统一 提交于 2020-08-07 04:40:06

问题


What's the recommended approach for declaring routes: with a forward slash or is it better to leave it out? Are there any benefits to using one over the other or is it just a matter of preference?

Is it better to use this:

 Route::get('/read', function(){
        $user = User::findOrFail(1);
            return $user;
    });

Or this instead:

Route::get('read', function(){
    $user = User::findOrFail(1);
        return $user;
});

Thanks in advance.


回答1:


It comes down to preference. When passing the route, it actually trims the forward slashes off, then formats it properly. In Illuminate/Routing/Router.php, all routes go through the prefix function, which looks like this:

protected function prefix($uri)
{
    return trim(trim($this->getLastGroupPrefix(), '/').'/'.trim($uri, '/'), '/') ?: '/';
}

So if you create a group prefix /test/ and and a uri of /route, it becomes test/route




回答2:


I also prefer without leading slash. You know it's forward slash.

There's no difference as it just explodes the slashes anyway.



来源:https://stackoverflow.com/questions/50935571/routes-in-laravel-with-or-without-a-forward-slash

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!