Don40
Don40

Reputation: 417

How to reuse custom functions in different Laravel controllers?

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?

Upvotes: 3

Views: 3840

Answers (2)

Omar Makled
Omar Makled

Reputation: 1876

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

Upvotes: 1

nakov
nakov

Reputation: 14318

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.

Upvotes: 4

Related Questions