successdav
4 months ago

Help me refactor this code its a bit lengthy

Posted 4 months ago by successdav

All am doing is: When creating a new learn and setting the order number, check to see if there already exists an item with that order if so increment the order.

The code achieve the end goal but I know it can be written better

here is my code

Store method in Controller:

public function store(Course $course, Request $request)
    {
        $this->validate(request(), [
            'body' => 'required|spamfree',
        ]);
        
        $learn = Learn::addLearn([
            'body' => request('body'),
            'course_id' => $course->id
        ]);
        return $learn;
    }

Logic to persist to database on Learn Model

static public function addLearn($learn)
    {
        $order = 1;
        if(static::whereOrder($order)->exists()){
            $order = self::incrementOrder($order);
        }

        $learn = self::create([
            'body' => $learn['body'],
            'course_id' => $learn['course_id'],
            'order' => $order
        ]);

        return $learn;
    }

    static public function incrementOrder($order)
    {
        while(static::whereOrder($order)->exists()) {
            $order++;
        }

        return $order;
    }

Please sign in or create an account to participate in this conversation.