Laravel 4 Controller Before and After function
laravel, laravel-4, php
Solution
According to the documentation, you can define before and after methods in your controllers in two ways.
With a filter name:
$this->beforeFilter('auth');
$this->afterFilter('something_else');
or with a closure:
$this->beforeFilter(function() {
// code
});
These would go in your base controller's `__construct` method.
Here's a complete example:
class BaseController extends Controller {
public function __construct()
{
// Always run csrf protection before the request when posting
$this->beforeFilter('csrf', array('on' => 'post'));
// Here's something that happens after the request
$this->afterFilter(function() {
// something
});
}
/**
* Setup the layout used by the controller.
*
* @return void
*/
protected function setupLayout()
{
if ( ! is_null($this->layout))
{
$this->layout = View::make($this->layout);
}
}
}
Problem
I have a Base Controller that all other controllers will extend it. I want to do some theme and validation and also loading widgets in its Before function. I know that i could handle this with Routes filter but i don't want to place my code inside router i want to every controllers actions first execute "Before function" and then execute "After function" of this Base controller like Laravel 3. ``` class FrontController extends \BaseController { protected $layout = 'home.index'; public function __construct() { } public function before() { // Do some theme and validation } public function __call($method, $parameters) { return Response::abort('404'); } ``` Update : I'm looking for a way that for example I could change theme based on a page config or load sidebars widgets after main controller completed its function and ... Because of that I want to access to $this.