Home >Backend Development >PHP Tutorial >Laravel route alternatives

Laravel route alternatives

Susan Sarandon
Susan SarandonOriginal
2025-01-05 06:42:441000browse

Laravel route alternatives

Earlier today I reacted on a post about Laravel Folio, and that got me thinking about all the ways you can set routes in Laravel. This is the outcome.

Laravel build in options

The out-of-the-box way to add routes is by using the files in the routes directory.
All the http verbs have a Route class equivalent. And for multiple verbs there are the route and any methods.

For all the above methods the route is coupled with a controller method in most cases. The Route class has a special method, view, in case the route doesn't require logic.
If it is a static page, I think the best way to do this is with an .html file in the public directory.

Skipping the routes directory files

Instead of adding the routes to the web.php file. It is possible to create a ServiceProvider that does the same thing.

namespace App\Providers;

use Illuminate\Support\ServiceProvider;

class WebRouteServiceProvider extends ServiceProvider
{

    /**
     * Define the routes for the application.
     *
     * @return void
     */
    public function boot()
    {
        parent::boot();

        Route::middleware('web')->group(function() {
          // routes
       });
    }
}

I suggest when you use this, add a comment in the web.php file. future you and other developers will thank you.

Folio

Folio can be seen as Route::view but from the side of the views. When you create a template in the resources/views/pages directory, the name of the template will become an url.

Both Folio and Route::view can lead to adding controller logic or even routing logic in the template. For me this is a code smell. Only display logic should be in templates.

Spatie Laravel route attributes

If you are envious about the way Symfony sets routes by default, you could install the Spatie Laravel route attributes package.

The major benefit is that the route is set in the same file as the code that produces the output.
The disadvantage of this way compared with the default way, is that for a route switch two files need changes instead of one.

All the small things

Whether you stick with default way of settings routes or using one of the alternatives is up to you. Just be careful with the view alternatives.

This is a feature of a great framework. If you don't like the default experience, with some minor changes you can make it the way you find it more useful.

The above is the detailed content of Laravel route alternatives. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn