Laravel and output buffering

7.3k views Asked by At

I have a problem with output buffering in laravel 4. This code works good in other frameworks but in laravel i get fatal error for ob_get_flush()

class Ajax
{
    public function __construct()
    {
        if ( Request::ajax() )
        {
            ob_clean();
            ob_start(function(){});
            register_shutdown_function(array(&$this,'setOutput'));

        }

    }

    public function setOutput()
    {
        $html = ob_get_flush();
    }

}

error :

ob_get_flush(): failed to delete and flush buffer. No buffer to delete or flush
2

There are 2 answers

1
rap-2-h On

It's "just" a Notice, not an Error. Your buffer content is empty, so PHP (through laravel) sends you a notice because it has nothing to do with ob_get_flush. Maybe notices are disabled in other frameworks you tried. According to this answer, you can do something like this, if you want to make it work even if your buffer is empty:

public function setOutput()
{
     if (ob_get_level() > 1) $html = ob_get_flush();
}

Hope it will help !

0
dasper On

Is it possible that the class is being called before Request::ajax() can return true?

If so then your constructor conditional would return false and ob_start would not be called. Perhaps you can move that part out of the conditional or try rewriting it to where you write the data to the object and then call renderOutput() and this method would have your ob calls in the proper order.