1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Laravelで /(トレイリング スラッシュ)がついているURLを扱うには

Posted at

やりたいこと

Laravelの標準ではURLのトレイリングスラッシュが削除されてしまうため、
削除されていないURLを取得・生成したい。

環境

Laravel 8.35.1
PHP 7.4.19

トレリングスラッシュがついたURLを取得する

Illuminate\Http\Requestクラスをオーバーライドする

app/Services/Vendor/Http/Request.php
use Illuminate\Http\Request as BaseRequest;

class Request extends BaseRequest
{
    /**
     * Get the URL (no query string) for the request.
     *
     * @return string
     */
    public function url()
    {
        return preg_replace('/\?.*/', '', $this->getUri());
    }
}

Requestクラスを上のオーバーライドしたクラスに置き換える

public/index.php
// use Illuminate\Http\Request;
use App\Services\Vendor\Http\Request;

トレイリングスラッシュがついたURLが取得出来る

$request->fullUrl(); // http://localhost/api/works/

トレイリングスラッシュがついたURLを生成する

Illuminate\Routing\UrlGeneratorクラスをオーバーライドする

app/Services/Vendor/Route/UrlGenerator.php
use Illuminate\Routing\UrlGenerator as BaseUrlGenerator;

class UrlGenerator extends BaseUrlGenerator
{
    /**
     * Create a new manager instance.
     *
     * @param BaseUrlGenerator $url
     */
    public function __construct(BaseUrlGenerator $url)
    {
        parent::__construct($url->routes, $url->request);
    }

    /**
     * Format the given URL segments into a single URL.
     *
     * @param string $root
     * @param string $path
     * @param null $route
     * @return string
     */
    public function format($root, $path, $route = null)
    {
        $path = parent::format($root, $path);

        $mathes = null;
        preg_match("/([^\/]+?)?$/", $path, $mathes);
        $last = $mathes[0] ?? '';

        if (strpos($last, ".") === false) {
            return $path . "/";
        }
        return $path;
    }
}

上のクラスを登録する

app/Providers/AppServiceProvider.php
    public function boot()
    {
        $url = $this->app['url'];
        $this->app->singleton('url', function () use ($url) {
            return new UrlGenerator($url);
        });
    }

トレイリングスラッシュがついたURLが生成出来る

route('api.works.index') // http://localhost/api/works/

以上

参考

https://readouble.com/laravel/4.2/ja/extending.html
https://qiita.com/watanuki_p/items/ce123404b569214ecff2

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?