Search code examples
laravelsimplify

How can I Simplify this code of Laravel 8?


I have this code in routes, is it possible to simplify it? Thanks

Route::get('/post1', function () { 
    return view("post1");
})->name("/post1");

Solution

  • There is nothing wrong with that code, the only way you can "simplify" that code, better to say "abstract it" is by creating a controller with a method that returns the view.

    In your case, if your route is very specific you can create a single action controller with the command:

    php artisan make:controller PostController -i.

    Then in the controller:

    public function __invoke(Request $request)
    {
        return view("post1");
    }
    

    And in your routes file:

    Route::post('/post1', PostController::class);
    

    More info in the Single Action Controller docs and in the views docs