Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where do I put custom code in Laravel

Tags:

laravel

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?

like image 802
user513788 Avatar asked Dec 17 '13 06:12

user513788


1 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/

like image 111
Albin N Avatar answered Jan 03 '23 10:01

Albin N