dongzi5062 2019-08-10 05:13
浏览 893
已采纳

Laravel:重构Controller store()和update()方法

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?

  • 写回答

3条回答 默认 最新

  • dongyong6045 2019-08-10 05:18
    关注

    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]);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?