Search code examples
laravelpost

Can a Laravel POST route return a view instead of redirecting to another route?


I have seen/worked on lot of projects where a Laravel POST route looking like this:

Route::post('/some-url', [SomeController::class, 'someMethod']);

And the controller with its method which takes care of the route looking like this:

class SomeController extends Controller
{
    public function someMethod(Request $request) {
        // My Logic to do something with the post data - $request
        return redirect("/some-other-url");
    }
}

have always redirected to a specific URL after doing something with the POST data, by convention.

I would like to know, if after processing a POST request, if it's okay to just return a view like what we do with GET requests? I know it works, but is it just convention or are there any issues in doing so?

Eg:

class SomeController extends Controller
{
    public function someMethod(Request $request) {
        // My Logic to do something with the post data - $request
        return view("somebladeview")->with(["result" => $result ]);
    }
}

Solution

  • The pattern is called post-redirect-get, or PRG. It is convention because POST should be used for requests that change data, whereas GET should be used to simply display data.

    If you return a view after a POST, the user can hit reload, and (probably unintentionally) change data again, eg buy something a second time. By using PRG, the user hitting reload simply reloads the last GET, which just re-displays something.

    NOTE: There is some advice in the comments on your question to ignore this convention. I think that is unwise and dangerous, these conventions exist for good reasons.