Laravel Dynamic Route

Asked

Viewed 492 times

0

I have the following question. It is correct to create a dynamic route to return my views, or I have to create a route for each controller and return the appropriate view?

Example of the code I’m using

route archive

Route::get('/{url?}/{url2?}/{url3?}', 'UrlController@getUrl');

controller

public function getUrl($url = null, $url2 = null, $url3 = null) {
    if (isset($url3)) {
        return view($url . '.' . $url2 . '.' . $url3);
    } elseif (isset($url2)) {
        return view($url . '.' . $url2);
    } elseif (isset($url)) {
        return view($url, ['name' => 'Romullo']);
    } else {
        return view('home');

    }
}

This code returns me exactly the view that is typed in the url or generates the error page correctly. But I was left in doubt among the many articles I have read. Is that correct or not? I must actually create route by route for each controller and view or I can call dynamically?

  • If you can do something with 10 lines and never need to move (unless you change the code a lot), why do it in 50? Maybe at some point you want something more specific, for example, that a route goes through a validation or something, in which case you can create a specific route and prioritize it

  • Why don’t you use the one recommended by the documentation? It seems to me that this way of writing generates a code difficult to maintain as the number of routes grows.

  • I don’t think there’s an A or a B, but cases and cases. But I can’t disagree with @Marabesi, who is very important to think about the readability of the code as much as performance or number of lines.

  • You can’t do it like that 'cause there’s gonna be a collision of routes ...

1 answer

0


I don’t know exactly what you want to do with this code. I think it will be better if you do separate routes. Depending on what you want to do it would be easier until you create a Factory with this dynamic route and use this Factory to send the guy to the controller.

The way you’re doing your code will become complex as you grow and it will become harder to maintain it and for other people to contribute.

Browser other questions tagged

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