LoginSignup
24
24

More than 1 year has passed since last update.

【Laravel】web.phpとapi.phpの違い

Last updated at Posted at 2020-11-24

Laravelのルーティングファイルについて

Laravelのルーティングファイルには、web.phpとapi.phpの2種類があります。

ルーティングファイルの違いについて

web.php

通常、ブラウザからHTTPリクエストをうけて、画面に表示するようなルーティングを設定する場合に使用する。
CSRF保護などの機能が有効になっているため外部からのPOSTができない。

api.php

外部からのHTTPリクエストをうけて、値を返却したりするようなルーティング(エンドポイント)を設定する場合に使用する。
CSRF保護が有効になっていないため外部からPOSTができる。

動作の違いについて

web.phpとapi.phpの動作の違いについては、Laravel6の場合、app/Http/Kernel.phpで設定されています。

api.phpにはVerifyCsrfTokenが入っていない

   /**
     * The application's route middleware groups.
     *
     * @var array
     */
    protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            // \Illuminate\Session\Middleware\AuthenticateSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],

        'api' => [
            'throttle:60,1',
            'bindings',
        ],
    ];

まとめ

  • Laravelではルーティングを設定するためのファイルが2種類ある
  • web.phpは画面表示する際のルーティングファイル
  • api.phpのルーティングは外部からのアクセス用のルーティングファイル
24
24
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
24
24