DEV Community

Lokman Musliu
Lokman Musliu

Posted on

Laravel Tip: Refactoring to lookup tables

Sometimes you find yourself in a situation where you have too many if statements in a controller. On a recent project that we were working on, we had a case where we had to show three different views based on the model type.

Our initial code looked something like this:

<?php

public function create(Report $report, $type)
{
    if ($type == 1)
        return view('items.inventory.create', ['report' => $report]);
    elseif ($type == 2)
        return view('items.stock.create', ['report' => $report]);
    elseif ($type == 3)
  return view('items.special.create', ['report' => $report]);
}
Enter fullscreen mode Exit fullscreen mode

Read full tutorial on our blog

Top comments (1)

Collapse
 
sloan profile image
Sloan the DEV Moderator

Hi there, we encourage authors to share their entire posts here on DEV, rather than mostly pointing to an external link. Doing so helps ensure that readers don’t have to jump around to too many different pages, and it helps focus the conversation right here in the comments section.

If you choose to do so, you also have the option to add a canonical URL directly to your post.