LoginSignup
11
7

More than 5 years have passed since last update.

LaravelのbeforeFilterを利用して特定のControllerやActionにAjax通信の判定をかける

Last updated at Posted at 2015-09-30

Laravelのfilterはルートだけではなく、Controller内に記載して特定のControllerやActionにだけ処理を適用することができます。
例えば、Route::resourceやRoute::controllerを利用している場合などに、ルーティングファイルでFilterをかけることはできないため、Controller側に記載し、ActionごとにFilterをかける必要があります。そんな場合の対応策を。

Filterを作成

app/filter.php
public function _filterAjax($route, $request)
{
    if (!Request::ajax())
        return Response::json('Ajax通信ではありません。');
    }
}

Controllerに適用

    public function __construct()
    {
        parent::__construct();
        $this->beforeFilter('_filterAjax');
    }

__constructのbeforeFilterでメソッドを呼ぶだけで、このControllerを実行する際に必ず実行されるようになります。
また、無名関数を作成しそこに直接記述することもできます。

    public function __construct()
    {
        parent::__construct();
        $this->beforeFilter(function()
        {
            if (!Request::ajax())
                return Response::json('Ajax通信ではありません。');
            }
        });
    }

特定のActionにだけ適用する

    public function __construct()
    {
        parent::__construct();
        $this->beforeFilter('_filterAjax', [
            'only' => [
                'update',
            ],
        ]);
    }

beforeFilterのonlyに指定すれば、指定したActionにのみにFilterがかかります。
なお、Filterをfilter.phpではなく、同一のControllerやBaseControllerに記述する場合は、メソッド名の前に@をつけて呼びだす必要があります。

    public function __construct()
    {
        parent::__construct();
        $this->beforeFilter('@_filterAjax', [
            'only' => [
                'update',
            ],
        ]);
    }

beforeFilterの指定方法あれこれ

filterのActionの指定方法は下記の指定ができます。

指定方法 内容
only 指定したActionのみ
except 指定したAction以外
on 指定したメソッドのみ[post,get,etc...]

onlyやonを組み合わせもできるので様々な状況で対応ができます。

    public function __construct()
    {
        parent::__construct();
        $this->beforeFilter('_filterAjax', [
            'on' => [
                'post',
            ],
            'only' => [
                'update',
            ],
        ]);
    }

記事はbeforeFilterのみでしたが、処理の後に行うafterFilterも同様に利用することができます。

11
7
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
11
7