Lim Heng Cheun
Lim Heng Cheun

Reputation: 229

Laravel Multiple module using one Controller

Now I have few modules created like Product, Sale, Category. I found out they actually using same function with similar process. For example update() in Controller :

Category

public function update($id)
{
        $instance = Category::findOrFail($id);

        $instance->fill(Input::all())->save();
}

Product

public function update($id)
{
        $instance = Product::findOrFail($id);

        $instance->fill(Input::all())->save();
}

How can I join it together to BaseController by just make the Model dynamic?

Upvotes: 1

Views: 404

Answers (1)

rdiz
rdiz

Reputation: 6176

Something like this:

abstract class ResourceController extends BaseController
{
    protected $entity;

    public function __construct(Model $entity){ //or Eloquent, depending on your import alias

        $this->entity = $entity;
    }


    public function update($id)
    {
        $instance = $this->entity->findOrFail( $id );

        $instance->fill( Input::all() )->save();
    }

}



class ProductController extends ResourceController{
    public function __construct(Product $entity){
        parent::__construct($entity);
    }
}

class CategoryController extends ResourceController{
    public function __construct(Category $entity){
        parent::__construct($entity);
    }
}

Upvotes: 1

Related Questions