Search code examples
phplaravellaravel-4rails-activerecordbefore-filter

Can we add before filters before method calls?


Take this Ruby on Rails example.

class SomeController < ApplicationController
  before_filter :generateRandomValue

  def generateRandomValue
     //generates a random value between 0 and 10
  end

  def getBoo
     //Return value generated by the method above
   end
end

If we call getBoo, class will run generateRandomValue first because it has a general scoped before filter.

We can also tweak this before filters in Ruby on Rails, like;

    method x,y,z runs before a method.
    method 1,2,3 runs before b,c,d method.
    method always, always runs. (think it like PHP's __construct())

Is there any way to set before filters before controller method calls in Laravel 4?

The main reason is, I want to DRY most of my code by applying before filters.

Thank you.


Solution

  • Yes - this is a new feature in Laravel 4.

    Taylor has a good video on it here you can watch - which shows it in action and the code to use.

    But in general you just add a filter to your constructor:

    Class ExampleController extends BaseController
    {
        public function __construct()
        {
            $this->beforeFilter('myfilter');        
            $this->beforeFilter('anotherfilter')->only('getBoo');       
        }
    }