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

2 Answers 2

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

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

Comments

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;

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.