Home » Php » Where do I put custom code in Laravel

Where do I put custom code in Laravel

Posted by: admin November 30, 2017 Leave a comment

Questions:

Good day,

I have some custom code from a previous non-mvc application. It’a all unit tested and stuff. Now, I need to put it in a laravel application. They are not controllers, or models or views? Does this mean I have to put them in the vendor folder with the Symfony and the Swiftmailer folders?

Answers:

Do you mean custom classes? Sometimes I put some of my classes in a separate directory, because as you said, they wouldn’t fit in either the model, view or controller (or the routes.php).

What I did was to create a new directory under app called libraries. You could name it whatever you want. Then you add it to the composer.json file autoload portion.

{
    "require": {
        "laravel/framework": "4.0.*",
    },
    "autoload": {
        "classmap": [
            "app/commands",
            "app/controllers",
            "app/models",
            "app/database/migrations",
            "app/database/seeds",
            "app/tests/TestCase.php",
            "app/libraries" // <---Added here
        ]
    },
    "scripts": {
        "pre-update-cmd": [
            "php artisan clear-compiled"
        ],
        "post-install-cmd": [
            "php artisan optimize"
        ],
        "post-update-cmd": [
            "php artisan optimize"
        ]
    },
    "config": {
        "preferred-install": "dist"
    },
    "minimum-stability": "dev"
}

Dont forget to run composer dump-autoload from your terminal or CMD to update your autoloader.

This will make the custom class autoload and you can use it where ever you want in your project by calling it like so YourClass::yourfunction($params)

If you prefer a screencast I would like to recommend Jeffrey Ways screencast about validation. He creates a custom class for validating a model. He also shows how to setup a custom class globally in your app. https://tutsplus.com/lesson/validation-services/

Questions:
Answers:

You should also add the path to /start/global.php

There is a more complete answer here:
What are the best practices and best places for laravel 4 helpers or basic functions?