How to make custom libraries in Laravel - as in codeigniter

Viewed 9303

i'm used to write a lot in codeigniter, where i try to place all logic code inside libraries instead of controllers.

The idea is a controller calls a library that calls a model to get data. So whatever is happening inside a library, can be called from multiple controllers easily, without rewriting code.

Now i'm baby stepping to laravel and i cannot find anything about custom libraries. I perfectly managed to call a model from a controller, but I want to have a controller calling a library and the library calling the model.

I'm not able to find libraries (not packages), do they exist in laravel ?

Thank you.

3 Answers
  1. First create Libraries directory inside app, then just create simple classes inside Libraries with functions which will call the models. remember to write

    namespace App\Libraries

    in every library you create.

  2. then in composer.json add this line "App\\Libraries\\": "src" as the result your composer.json will become something like this

     `"autoload":{
         "psr-4": {
          "App\\": "app/",
          "App\\Libraries\\": "src",
    
     },}`
    
  3. simply in your controller instantiate the library you want and use it's functions.

Related