Jordan Ramstad
Jordan Ramstad

Reputation: 179

Laravel 5 handle return from controller

I have an application that has many views that use need to inject some code into specific sections of the view. In a previous application I had used the root controller to do this and used special functions however it kind of changes the normal workflow of creating a laravel application to do it that way.

Basically say you have a create function

public function create()
{
   return view('something');
}

And you want to add something to a specific section, normally you would do this in the view and add any data needed to the call for the view. I want to do this in the controller but since any function returning a view would show the same thing in this case I want to simplify it a bit.

I tried looking but I could not find anything about post processing on a controller function, is there anything like that? Here is an example.

public function beforeRender($instance)
{
   if ($instance instanceof View)
   {
      $instance->getFactory()->inject('context-menu', $someData);
   }

   return $instance;
}

The beforeRender function would run after the create function in the controller and alter the return, allowing for a special return for anything with a view.

So my question is if there is anything like this in laravel 5 (or similar) and how I might do it. In a previous app I had remade how laravel handled controllers but I want to avoid doing that this time.

Upvotes: 0

Views: 391

Answers (1)

Yauheni Prakopchyk
Yauheni Prakopchyk

Reputation: 10912

If I'm not mistaken, the feature is to be implemented in Laravel 5.1. You may grab dev version or wait until release is out.

Service Injection in Laravel docs:

@inject('metrics', 'App\Services\MetricsService')

<div>
    Monthly Revenue: {{ $metrics->monthlyRevenue() }}.
</div>

You may check Code Composers as well. The approach is a bit different, keeping views spick and span:

public function compose(View $view)
{
    $view->with('count', $this->users->count());
}

Upvotes: 1

Related Questions