Home > Net >  How to improve multiple eloquent conditions?
How to improve multiple eloquent conditions?

Time:10-17

Here is a default eloquent condition:

if($request->has("parent")) =>  {

Specializatio::where('id', $request->id)
    ->when($request->parentid, function($query) use ($request){
        return $query->where('parent_id', $request->parent_id);
    })

}

It grows up so fast into long list of conditions .when based request object. Is there any flexibale mechanism to manage it, maybe devide in another class, helper?

CodePudding user response:

Maybe query scopes and short hand functions will make your code a bit cleaner.

class Specialization extends Model
{
    public function scopeParent($query, $parentId)
    {
        return $query->where('parent_id', $parentId);
    }
}

Specialization::whereKey($request->id)
    ->when($request->filled('parent_id'), fn ($query) => $query->parent($request->parent_id));
  • Related