Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Routes in Laravel with or without a forward slash?

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.

like image 667
Mirza Sisic Avatar asked Jun 19 '18 19:06

Mirza Sisic


1 Answers

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

like image 172
aynber Avatar answered Oct 18 '22 02:10

aynber