weekapaug
weekapaug

Reputation: 332

Laravel controller with included files issue

In order to consolidate some bulky code in a controller I have been able to do this inside function

public function myCustomFunction(Request $request){
 include(app_path() . '/myFunctions/myCustomFunction1.php');
}

It does successfully work but by doing the include, I noticed it doesnt carry the namespace and/or other variables set in the controller.

If its just a simple model it needs I was able to add

Use \App\myModel;

to the top of the controller and it runs the code just fine as if its part of the controller.

What I am having issue with is when I want to run validation. I cant figure out what to "use" to work on the included page.

If I run my logic in the controller without doing include it works, but if put inside the include it does not, and I get NO errors either.

I tried this inside the include page to activate the validation from within the include file

namespace App\Http\Controllers;
use Validator;
use Request;

which mimics the original controller, but still does not work. Is what I'm trying to do possible but I'm doing something wrong? Or am I doing something that will never work? If all else fails I can keep the code within the actual controller to make it work, but I'm trying to accomplish some sort of clarity on complex controllers. Such as...

public function myCustomFunction(Request $request){
    if(request('value1')=='1'){
      include(app_path() . '/myFunctions/myCustomFunction1.php');
    }else{
      include(app_path() . '/myFunctions/myCustomFunction2.php');
    }
}

This structure is already working on anything that doesn't need validation so I'm hoping there is a simple way to hook the include page into the same set of validation tools the original controller has access to.

Upvotes: 0

Views: 735

Answers (1)

Mike Foxtech
Mike Foxtech

Reputation: 1651

In the controller, so include the files incorrectly. It's best for you to create a Helpers folder in the app folder, in it create classes with your functions.

namespace App\Helpers;

class HelpersOne {
  public function myFunctionOne(){.../*youre code*/}
  public function myFunctionTwo(){.../*youre code*/}
}

And already in your controller you can call these classes.

use App\Helpers\HelpersOne;
...
public function myCustomFunction(Request $request){
    if(request('value1')=='1'){
      $myFunction = new HelpersOne();
      $myFunction->myFunctionOne(); 
    }else{
      $myFunction = new HelpersTwo();
      $myFunction->myFunctionTwo(); 
    }
}

Upvotes: 2

Related Questions