0

I have various controller functions where I have a large chunk of code (for an API call) which repeats in other functions a lot of time. Is there a @include equivalent to just copy/paste the codes in my controller. This will be much easier to read and follow through.

In my controller, something like this

    public function store () 
    {
       if ($company->name = 'XYX')
       {
           @include('xyzcontrollercode') 
       }

       if ($company->name = 'DEF')
       {
           @include('defcontrollercode') 
       }
   }

The includes - 'xyzcontrollercode' will have a large chunk of logic which will implement once the 'if' condition matches.

Any way to achieve this kind of functionality for controllers?

Cowgirl
  • 1,454
  • 5
  • 19
  • 40
  • You can use helpers or a trait where you can create a method with your logic and then call it in the if statment – Maraboc Oct 25 '17 at 18:11
  • I tried using helpers, but the helpers function won't have the includes, at least the way I am implementing it – Cowgirl Oct 25 '17 at 18:13
  • A simple example please – Cowgirl Oct 25 '17 at 18:14
  • Another way to do this is to create a "Helper" class with static functions. – Laerte Oct 25 '17 at 18:32
  • maybe this can help you: https://stackoverflow.com/questions/28290332/best-practices-for-custom-helpers-on-laravel-5 – Rusben Guzman Oct 25 '17 at 18:37
  • Did you get it or i can add an answer if you didn't like the idea of inherit in the given answer also note that with the helper you will not use include but you will call the method directly ! – Maraboc Oct 25 '17 at 19:17

1 Answers1

1

You can create a general controller and inherit from it.

For example:

class GeneralController extends Controller
{
    public function operation(){
        // do some things ...
    }
}

class HomeController extends GeneralController
{
    public function store(){
        // do some things ...

        if ($company->name == 'XYX')
        {
            $this->operation(); 
        }

        // do something ...
    }
}

Or you can use dependency injection

SLDev
  • 336
  • 2
  • 6