user513788
user513788

Reputation: 103

Where do I put custom code in 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?

Upvotes: 5

Views: 5351

Answers (2)

Joeri
Joeri

Reputation: 2308

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?

Upvotes: 0

Albin N
Albin N

Reputation: 1401

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/

Upvotes: 11

Related Questions