3

I have build several functions that I reuse in almost all of my controllers, at the moment I have to paste every function in every controller in order to work. The code looks really messy and it is quite difficult to make edists as I get lost in the lines.

How or where can I declare my functions so I can reuse them in all controllers witout pasting them there?

1
  • 1
    You can make helper functions, or can make one class consisting of functions, then in your controller you can use those class functions Commented Apr 21, 2019 at 7:21

2 Answers 2

4

You can create your own BaseController in which you can store the functions that you reuse, and then your controller that needs those function can extend from the BaseController.

Another approach is to create a custom helper file, which will contain the functions that you reuse. For example create a helpers.php file in the app folder, and then add that in the composer.json to autoload.

"autoload": {
    "psr-4": {
        "App\\": "app/"
    },
    "files": [
      "app/helpers.php" // here is the helpers file to autoload.
    ],
        "classmap": [
        "database/seeds",
        "database/factories"
    ]
},

After this run

composer dump-autoload

in your terminal.

Sign up to request clarification or add additional context in comments.

Comments

1

I prefer to create a service layer and inject into a controller

class AnyController {
    public function __construct(MyService $myService)
    {
        $this->myService = $myService;
    }

    public function anyFunction()
    {
        // $this->myService->foo()
    }
}

Or you can inject into a particular action

class AnyController {
    public function anyFunction(MyService $myService)
    {
        // $this->myService->foo()
    }
}

Read more

https://laravel.com/docs/5.8/container

Comments

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.