3
5

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 5 years have passed since last update.

LaravelのテンプレートでCDNにある静的ファイルへのURLを生成する

Last updated at Posted at 2017-04-21

概要

Laravelには静的なファイルへのURLを生成するassetというヘルパー関数が存在し、
普通に使うとWEBサーバーと同じ場所(オリジン)でパスを生成してくれます。

{{asset('css/style.css')}}
↓
https://www.example.com/css/style.css

しかし大規模なサービスの場合、静的なファイルはCDNを使って別の場所から配信していたりすると思います。
その場合assetヘルパーが使えないので、別途方法を考える必要があります。
色々方法はあるみたいですが、
今回は、カスタムディレクティブを使ってそれを実現してみました。

修正

app/Providers/AppServiceProvider.php
    public function boot()
    {
        // ...

        //静的ファイルURL生成
        Blade::directive('asset', function($path){
            return "<?php echo app('url')->assetFrom(config('app.asset_url'), $path); ?>";
        });
    }
config/app.php
return [
    // ...

    'asset_url' => env('APP_ASSET_URL'),

    // ...
];
.env
APP_ASSET_URL=https://asset.example.com

使い方

@asset('css/style.css')
↓
https://asset.example.com/css/style.css

カスタムディレクティブなので{{}}は使いませんが、
もともとのassetヘルパーと近い使用感で使えると思います。

3
5
1

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
3
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?