Data Interceptor for your views — Laravel 5.5

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.

1- Extend the ViewServiceProvider

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 createFactory

<?php

namespace
App\Providers;

use App\Support\View\MyViewFactory;
use Illuminate\View\ViewServiceProvider as BaseViewServiceProvider;

class ViewServiceProvider extends BaseViewServiceProvider
{
protected function createFactory($resolver, $finder, $events)
{
return new MyViewFactory($resolver, $finder, $events);
}
}

2- Don’t forget to swap the Service Provider settings

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\App\Providers\ViewServiceProvider .

3- Create the custom View Factory

I decided to create mine in application/App/Support/View as follows:

<?php

namespace
App\Support\View;

use Illuminate\View\Factory;

class MyViewFactory extends Factory
{
protected function viewInstance($view, $path, $data)
{
return new MyView($this, $this->getEngineFromPath($path), $view, $path, $data);
}
}

4- Implement data interception in your custom View

The gatherData method will be called right before providing data to views. That is the perfect place to intercept all of the data provided.

<?php

namespace
App\Support\View;

use Illuminate\View\View;

class MyView extends View
{
protected function gatherData()
{
$data = parent::gatherData();

return array_merge($data, ['intercepted' => true]);
}
}

5- See the result!

Now just open the welcome.blade.php file and add a snippet that allows you to test the interception:

@if($intercepted)
<h1>INTERCEPTED!</h1>
@endif

And you’ll be able to see it once you open the page.

More by Marco Aurélio Deleu

Topics of interest

More Related Stories