bart2puck
bart2puck

Reputation: 2522

Laravel Use a folder instead of 1 controller

I have dozens of controllers that i need to use in a main controller I have

Instead of doing something like:

Use App\Http\Controllers\Animals\Cat;
Use App\Http\Controllers\Animals\Dog;
Use App\Http\Controllers\Animals\Fish;
Use App\Http\Controllers\Animals\Bird;
Use App\Http\Controllers\Animals\Tiger;
Use App\Http\Controllers\Animals\Shark;

class MyAnimals extends BaseController
{
    $cats = Cat::getCat();
    $dogs = Dog::getDog();
    // etc
}

Is there a way I can just use an entire folder? something like:

Use App\Http\Controllers\Animals\
      
class MyAnimals extends BaseController
{
    $cats = Cat::getCat();
    $dogs = Dog::getDog();
    // etc
}

I know this has probably been answered a lot, I just cant find it anywhere.

Upvotes: 0

Views: 32

Answers (2)

Bulent
Bulent

Reputation: 3411

Maybe something like this:

Use App\Http\Controllers\Animals\{
    Cat, Dog, Fish, Bird, Tiger, Shark
};

If you want to make it dynamic, you can create a function to read the folder content and call each class one by one.

public function handle()
{
    $animals = [];

    foreach ((new Filesystem)->files(__DIR__ . '/Animals') as $animal) {
        $animal = str_replace('.php', '', $animal);

        $animals[$animal] = (__NAMESPACE__ . "\\{$animal}")::get();
    }

    return $animals;
}

Upvotes: 1

IGP
IGP

Reputation: 15786

If your controllers share a namespace, then you don't need to include them.

namespace App\Http\Controllers\Animals;

class MyAnimals extends BaseController
{
    $cats = Cat::getCat(); // Cat here is assumed to be App\Http\Controllers\Animals\Cat;
}

Also, the keyword is use, not Use. A case-sensitive server could give you problems with that.

Upvotes: 1

Related Questions