Pietro Bonfim
Pietro Bonfim

Reputation: 49

Laravel: Refactoring Controller store() and update() methods

I'm developing a Laravel Web App and I need insight in refactoring my Controller.

I noticed that my Controller store() and update() methods are VERY similiar. So similar that the only line that changes are the following: In the store() method I use $deck = new Deck(); and in the update() method I use $deck = Deck::find($id);. These are the only lines that change in these 140 line each methods inside the Controller.

How can I refactor or to where should I extract this code? My first thought was to create a Trait and put the method there, but that doesn't seem right, or does it?

Upvotes: 1

Views: 736

Answers (3)

Franklyn Kleiton
Franklyn Kleiton

Reputation: 51

If you want to keep the application logic in your controller, you can make a function to your duplicate code, then pass the Deck object in the parameter.

  public function store()
  {
    $deck = new Deck();
    $this->save($deck);
  }

  public function update()
  {
    Deck::find($id);
    $this->save($deck);
  }

  private function save(Deck $deck)
  {
    // Duplicate Code goes here
  }

I hope I've helped

Upvotes: 1

My suggestion is to keep it simple. I would create a private function with the duplicated code and call it from store() and update() functions.

Upvotes: 0

nakov
nakov

Reputation: 14268

I won't advise on using a single method for both, but not knowing your use case you can use the firstOrNew helper method, which will return the Deck if it exists by the id given or it will make a new instance for you. So use this:

Deck::firstOrNew(['id' => $id]);

Upvotes: 0

Related Questions