Jeremy
Jeremy

Reputation: 1952

How to optimize a part of my controller which will be repeated in several others

I have a store function in my controller which I use to add data to my model.

In this store function, I have a piece of code that is used to add an expense in the ʻexpends` table

public function store(Request $request) {
    $model = Model::create([
        'name' => $request->name
    ])

    if ($request->add_expends == true) {
        Expend::create([
            'amount' => $request->amount
        ])
    }
}

The problem is, this piece of expense add code is used on multiple controllers (more than 10) across my application.

Is there a way to make this code reusable?

This is quite annoying because if I have to make a change I would have to do it in ten controllers and that's a problem.

Example of what I want to avoid :

public function store(Request $request) {
    $model = Model2::create([
        'name' => $request->name
    ])

    if ($request->add_expends == true) {
        Expend::create([
            'amount' => $request->amount
        ])
    }
}

public function store(Request $request) {
    $model = Model3::create([
        'name' => $request->name
    ])

    if ($request->add_expends == true) {
        Expend::create([
            'amount' => $request->amount
        ])
    }
}

Upvotes: 0

Views: 70

Answers (1)

yrv16
yrv16

Reputation: 2275

In your case I would use some trait. For example create a folder app/Http/Controllers/Traits and put there your trait ExpendTrait

<?php

namespace App\Http\Controllers\Traits;

Trait ExpendTrait {

    private function createExpend()
    {
        if (request()->add_expends == true) {
           Expend::create([
               'amount' => request()->amount
           ]);
        }    
    }
}

Now use it in each of your controllers

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Controllers\Traits\ExpendTrait;

class MyController extends Controller
{
    use ExpendTrait;          

    public function store(Request $request) {
       $model = Model::create([
         'name' => $request->name
       ]);

       $this->createExpend();
    }
}

Upvotes: 1

Related Questions