0

I have some php lines which will be used very often in my application. So I would like to build a function and call it every where in my app. My function could be :

static function array_matiere($id_ecole) {
     return $something;
}

I tried to put this code in a controller and then call it like that :

$liste_matieres = MatieresController::array_matieres(Session::get('id_ecole'));

It works, but where to put this kind of function ? in the controller ? in a method file ? what is the best practice ?

Thanks for your responses.

Dominique

Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
Dom
  • 2,984
  • 3
  • 34
  • 64

2 Answers2

2

There are multiple ways to implement this. look here

Method 1 This method is highly suggested by Laravel Expert ( JeffreyWay)

If your helper functions are similar to the way laravel 5 ones work, i.e Illuminate/Support/helpers.php you could just create a helpers.php and have composer do the autoloading for you.

Edit your composer.json file and add the file to the autoloading key. In my example my app is called Tasky so just add the files key and reference helpers.php.

"autoload": {
    "classmap": [
        "database"
    ],
    "psr-4": {
        "Tasky\\": "app/"
    },
    "files": [
        "app/Support/helpers.php"
    ]
},

That way you just create your file inside app/Support/helpers.php and all your common function based view helpers or other helpers can go here. If you take the class based approach then the above is great.

Also then remember to just run the following once.

$ composer dumpautoload

Source

Method 2

Please Follow the link and read answer & Its comments

Community
  • 1
  • 1
Qazi
  • 5,015
  • 8
  • 42
  • 62
0

Whenever u need to include a piece of code providing some functionality through out your application then the best way in Laravel is to make Service class inside app/Services and then you can use that class anywhere in your application using

   use App\Services\YourServiceName;
pritesh
  • 2,162
  • 18
  • 24