Heyaj05's avatar

How to achieve DRY principle - in an instance where you are trying to update either a single model or a collection of the same model?

I have a model a - that has a completed_at and a status property. When a user intimates a request via the api. I call a service class method called complete and pass the model to it via the controller. And it sets the completed_at and status property to todays date and “complete”

I also have a job that runs daily that needs to update multiple records of the same model to complete. Sometimes in 1000s.

I can call the same method in the service class discussed above by using a for each method. But that’s not optimal i rather update multiple in bulk.

Now I am kind of lost in how this should work - since the api only passes a single model and the job passes a collection

0 likes
2 replies
Sergiu17's avatar

With minimum amount of code, I'd probably change the api, I'll wrap the singe model into a collection, then your service will accept a collection

class ServiceClass {
	public function update(Collection $collection)
	{
		DB::table('your_table')->update(['completed_at' => now(), 'status' => 'complete'])
			->where(['id' => $collection->pluck('id')->toArray()); 
	}
}

// api
$user = auth()->user();
$this->serviceClass->update(collect($user));

// job
$users = User::limit(10)->get();
$this->serviceClass->update($users);
Heyaj05's avatar

Is this a good way to do it? Regarding the single update api endpoint will response with the model, the job does not care about a response, but in the future if there is an api end point that requires a bulk update it will likely require a response of the collection?

Or having bull create/update as separate is better ? What about an example where there is an orders model - that either the user can update be to completed or a job that does that?

Please or to participate in this conversation.