In this example we will learn how to remove index.php from URL in Laravel.

app/Providers/RouteServiceProvider.php:

Add this code to boot() method:

$this->removeIndexPHPFromURL();

And add this function:

/**
 * Remove index.php
 *
 * @return response()
 */
protected function removeIndexPHPFromURL()
{
    if (Str::contains(request()->getRequestUri(), 'index.php')) {
        $url = str_replace('index.php', '', request()->getRequestUri());

        if (strlen($url) > 0) {
            header("Location: $url", true, 301);
            exit;
        }
    }
}

Now if you open URL like below:

https://example.com/index.php/contact-us

will redirect to:

https://example.com/contact-us