Laravel Tip: Refactoring to lookup tables

lokman musliu
Lokman Musliu

March 7, 2021 · 3 min read · 4,077 views

Laravel HOT TIP Blogpost Image

Streamlining Laravel Development with Lookup Tables

As Laravel developers, we frequently face the challenge of managing unwieldy code cluttered with a plethora of if statements, particularly within controllers. This tangled web of conditional logic not only hampers maintainability but also complicates the refactoring process, becoming more problematic as project complexity escalates. In this article, we offer a strategic approach to conquer this widespread issue, drawing from our experience with a recent project. We'll guide you through the process of refactoring your code by implementing lookup tables, ultimately enhancing its readability and maintainability. Join us as we transform convoluted code into a model of clarity and efficiency.

Addressing Complexity: Tailoring Views to Model Types

In a recent endeavor, we were tasked with presenting three distinct views, each contingent upon the type of model in play. Initially, our approach resulted in code that resembled the following structure:

<?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]);
}

While this code works, it's not ideal. If we have to duplicate this logic in other methods, it will become a burden to refactor in the future.

The Solution: Introducing Constants in Our Model

The first step in our refactoring process is to introduce constants in our Item model. This makes the code more readable and easier to manage for the three different types. Here's how we did it:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Item extends Model
{
    use HasFactory;

    const INVENTORY = 1;
    const STOCK = 2;
    const SPECIAL = 3;
    
}

Now that we have the constants in our model file we can go back to the controller and introduce a new method that handles the correct routing based on the item type.

Refactoring the Controller: A New Method for Routing

Inside our controller we need a new protected function that will return the route based on the type, this function will only accept a $type. Then, inside the route of our create a function in the controller we can replace all the if statements with a single line of code.

<?php

namespace App\Http\Controllers;

use App\Models\Report;
use App\Models\Item;
use Illuminate\Http\Request;

class ItemController extends Controller
{
  
  public function create(Report $report, $type)
  {
    return view($this->filterItems($type), ['report' => $report]);
  }
  
  
  protected function filterItems($type)
  {
    $items = [
      Item::INVENTORY => 'items.inventory.create',
      Item::STOCK => 'items.stock.create',
      Item::SPECIAL => 'items.special.create',
    ];
  
    return $items[$type];
  }
  
}

And there you have it! Now, whenever we navigate to the create route with a specific type parameter, our streamlined function, filterItems, intelligently discerns the type, be it 1, 2, or 3, and promptly guides us to the corresponding view.

This method is particularly useful when you're grappling with intricate if/else statements and aim to tidy up your code for enhanced readability. By adopting this technique, you can simplify complex logical processes and maintain a clean, elegant codebase.


Bring Your Ideas to Life 🚀

If you need help with a Laravel project let's get in touch.

Lucky Media is proud to be recognized as a Top Laravel Development Agency

lokman musliu
Lokman Musliu

Founder and CEO of Lucky Media

Technologies:

Laravel
Heading Pattern

Related Posts

Stay up to date

Be updated with all news, products and tips we share!