Chan
Chan

Reputation: 1959

How to do filter on specified controller action in Laravel

I have CartController route filter seems only can bind on controller or get, can I do the auth filter on "action"?

for example:

<?php

CartController extends BaseController {

    public function getIndex() {
        // not need filter
    }

    public function getList()
    {
        // not need filter
    }

    public function getCheck()
    {
        // need to filter
    }

}

Upvotes: 2

Views: 5807

Answers (4)

nsbucky
nsbucky

Reputation: 328

I had a similar issue with a resource controller and was able to do this:

$this->beforeFilter('admin', [ 'except' => ['index','show'] ]);

Upvotes: 0

Sashel Niles Gruber
Sashel Niles Gruber

Reputation: 1221

You can set the BaseController beforeFilter() Action in your Class constructor and pass the Actions you want filtered as an 'only' keyed Array as the second Argument.

$this->beforeFilter('filtername', 
                    array('only' => array('fooAction', 'barAction')));

Using your example code:

<?php

CartController extends BaseController {

    public function __construct() {

        $this->beforeFilter('filtername', array('only' =>
                            array('getCheck')));
    }

    public function getIndex() {
        // not need filter
    }

    public function getList()
    {
        // not need filter
    }

    public function getCheck()
    {
        // need to filter
    }

}

Source: Laravel Docs: Controller Filter

Upvotes: 11

fideloper
fideloper

Reputation: 12293

You can call the filter in the method you need it in.

See the documentation here to see what that looks like in code.

 $this->beforeFilter('my-filter-name');

Upvotes: 0

Herman Tran
Herman Tran

Reputation: 1591

It seems you want to mix RESTful and normal methods (get/post vs action) together in the same controller, and at least in Laravel 3 this couldn't be done.

For filtering, you can look into controller filters where you can specific the auth filter for specific methods or go the other way and exclude certain methods from the filter.

Upvotes: 0

Related Questions