How to run code before all my methods inside controller in Laravel 4?

before-filter, controller, laravel, laravel-4, php

Solution

Laravel 5.1+

This has been deprecated in favour of Middleware.

Laravel 4

You could set the `beforeFilter` like this:

class ContentController extends BaseController {
    function __construct() {
        // this function will run before every action in the controller
        $this->beforeFilter(function()
        {
            // this will make the variable $myvar available in your view
            $this->layout->with('myvar', 'some-data');
        });
    }
}

Problem

I have Content controller with REST methods (index..create..store..) and i want to run some code before any of those methods run. what i am trying to do is to set var for my layout with some data that is relevant to all my methods within Content controller: ``` $this->layout->myvar = 'some-data'; ``` I tried to do something like that: ``` class ContentController extends BaseController { function __construct() { $this->layout->myvar= 'some-data'; } .. ``` but it doesn't seems to work. i get "Attempt to assign property of non-object" error.

Original source