5
0

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 のURLに対するアクセスで動的な JavaScript を返す

Last updated at Posted at 2018-06-26

ルートに対するアクセス時にセッション等を利用してユーザーを判別し、
ユーザーごとに異なるJavaScriptを返すというのを試してみたので、その際の関連メモです。

resources/views/dynamic/script.blade.php
// BladeテンプレートにそのままJavaScriptを記述してます
(function(){
  window.App = {
    env: '{{ config('app.env') }}'
  }
})()
routes/web.php
Route::prefix('dynamic')->group(function () {
    Route::get('my-script.js', function () {
        return response()->view('dynamic/script', [], 200, [
            'Content-Type' => 'application/javascript; charset=UTF-8',
        ]);
    });
});
<script src="/dynamic/my-script.js"></script>

Content-Type を指定するために、
ヘルパー関数の response() が返す ResponseFactory の、 view() というメソッドを利用しています。
(参考: Illuminate\Contracts\Routing\ResponseFactory | Laravel API)


試したはいいけど出番は無かったです。:wink:

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?