phplogicslim-3nested-if

How to simplify if else with four different conditions


How can I simplifyy this code of mine?

enter image description here


Solution

  • You can save the result of Carbon::*() into a variable and call its members.

    if (empty($startDate)) {
        $carbon = Carbon::now();
    } else {
        $carbon = Carbon::createFromFormat(...);
    }
    $post->start_at = $carbon;
    if (empty($endDate)) {
        $post->end_at = $carbon->endOfDay(); 
    } else {
        $post->end_at = Carbon::createFromFormat(...);
    }