Groups of routes with default values in Laravel

Asked

Viewed 249 times

1

I need to understand how I create routes with default values (it would be the default that we have in function switch PHP). I’m looking for something like:

Route::group(['prefix' => '/'], ['as' => 'public'], function(){

    Route::get('/{userid}', function () {
        return 'Perfil publico do usuário';
    });

    //rota de exemplo do que estou procurando, esta seria a default
    //caso o usuario não tenha buscado nenhum outro usuario no site
    Route::get('/', function(){
        return 'Página inicial do site'
    });

});

What is the best method to generate this type of route? Is there any default function for route groups?

1 answer

1


You can simply put a question (?) at the end of {userid}.

Therefore, you set the default value for the parameter variable, which represents the id passed in the url.

Route::get('/{userid?}', function ($userid = null) {
     if ($userId === null) {
         //Lógica para acesso feito apenas com a '/'
     } else {
         Usuario:findOrFail($userId);
         ...
    }
});

Then we would have two approaches to the same route:

meu.site/

and

meu.site/1
  • 1

    Excellent! I didn’t think I could make conditionals within a same get rsrs thanks!

  • 1

    I think you can do it your way. However, you would have to state the route / before the /{userid}. I speak from experience of the "precedence" of the declaration of the routes in Laravel 4 :)

  • Yes Wallace, I ended up hitting another key, because doing so is functional within the controllers, ex: if I want a registration form, if my user sends an id (edit) I do something, if not (new user) ;D

Browser other questions tagged

You are not signed in. Login or sign up in order to post.