0

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.

1 Answer 1

1

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());
}
Sign up to request clarification or add additional context in comments.

3 Comments

I don't think its what I am looking for but it does get my mind working in different ways to think about it. I want to avoid adding the same blocks of code for sections that are the same for multiple controller functions.
You may check Code Composers as well. The approach is a bit different, keeping views spick and span.
Thank you! I can never thing of the right search terms for these things but that looks like its exactly what I am looking for, right down to using service providers to define them.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.