Create new classes in laravel 5.2

23,218

Solution 1

you can just create those classes in your app folder (or in subfolder for example we create a Libraries folder with all the utilities). Just include a use App\YourClass; before using those classes and laravel will include the classes for you

Solution 2

Laravel 5.* is autoloaded using PSR-4, within the app/ directory. You can see this in the composer.json file.

  "autoload": {
    "classmap": [
        "database/seeds",
        "database/factories"
    ],
    "psr-4": {
        "App\\": "app/"
    }
},

Basically, you could create another directory within app, and then namespace your files in there as appropriate:

app/folder1/folder2/SomeClass.php.

Then, within your SomeClass.php, make sure you namespace it:

<?php namespace App\folder1\folder2;

class Someclass {}

Now, you can access this class using the namespace within your classes:

use App\folder1\folder2\SomeClass;

Solution 3

You can create your classes as usual, but don't forget to include them into composer.json autoload section:

"autoload": {
    "classmap": [
        "App\MyClassesNamespace"
....

And then run composer dumpauto command to rebuild autoloader file. If you'll not do this, you'll not be able to use your classes in your application.

Share:
23,218
Admin
Author by

Admin

Updated on October 24, 2020

Comments

  • Admin
    Admin over 3 years

    I'm working with Laravel framework.

    I have a question regarding classes creation. To explain my question, i will give you an example:

    class articleController extends Controller{
        public function bla(){
            $a = new MyNewClass($colorfulVariable);
            $b = $a->createSomething(new MySecondNewClass());
        }
    }
    

    Now, the classes MyNewClass and MySecondNewClass do not exist, I want to create them, use them in every controller I want, just like I use the Redirect or Request classes that Laravel offers.

    How can i create this classes? Make a new functions to use them in my laravel project?