A couple of days ago I saw a message on Laravel Internals from Colin Viebrock asking about intercepting data passed from controllers to the view. Here is how I did it.
Using artisan we can just
php artisan make:provider ViewServiceProvider to get us started. In the new service provider, we’re going to extend the default one and simply override the method
use Illuminate\View\ViewServiceProvider as BaseViewServiceProvider;
class ViewServiceProvider extends BaseViewServiceProvider
protected function createFactory($resolver, $finder, $events)
return new MyViewFactory($resolver, $finder, $events);
Inside the application/config/app.php there’s a list of providers that will boot up. Let’s remove the
Illuminate default one and replace it with the one we created on step 1. Should be
I decided to create mine in application/App/Support/View as follows:
class MyViewFactory extends Factory
protected function viewInstance($view, $path, $data)
return new MyView($this, $this->getEngineFromPath($path), $view, $path, $data);
gatherData method will be called right before providing data to views. That is the perfect place to intercept all of the data provided.
class MyView extends View
protected function gatherData()
$data = parent::gatherData();
return array_merge($data, ['intercepted' => true]);
Now just open the
welcome.blade.php file and add a snippet that allows you to test the interception:
And you’ll be able to see it once you open the page.