Laravel Tip: Refactoring to lookup tables

Laravel HOT TIP Blogpost Image

Published:March 7, 2021

Updated: November 15, 2023

Views: 3,963

Laravel

Leveraging Lookup Tables for Cleaner Code

In the world of Laravel development, we often encounter situations where our code becomes cluttered with numerous if statements, especially in controllers. This can lead to code that's hard to maintain and refactor, particularly as the complexity of the project grows. In this article, we'll explore a practical solution to this common problem, using a recent project as an example. We'll demonstrate how to refactor your code using lookup tables, making it more readable and maintainable.

The Challenge: Multiple Views Based on Model Type

In our recent project, we had to display 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]);
}

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

That's it! So, when we hit the create route with the current type, it will go through the function filterItems and based on the type (1, 2 or 3), it will redirect to that view.

You can use this technique whenever you are dealing with complex if/else statements and want to cleanup the code to be more readable.

Conclusion: Cleaner Code with Lookup Tables

This technique is a powerful tool for dealing with complex if/else statements and cleaning up your code to be more readable. It's just one of many ways we strive to deliver high-quality Laravel development at Lucky Media. For more Laravel tips and insights, check out our blog.


Bring Your Ideas to Life 🚀

Accelerate Your Business with a Top Laravel Development Agency

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 by Clutch, a leading B2B ratings and reviews platform.

Our Services and Specializations

At Lucky Media, we offer a range of services including website development, web application development, and mobile apps development. We specialize in Statamic, React Native, Next.js, AI and ML solutions. We also provide staff augmentation and TALL stack development services.

Case Studies: Our Work in Action

For more insights into our work, check out our case studies on revolutionising lead generation with AI, customized coaching site, healthcare digitization, next-level performance, lead generation and patient journey, WordPress to Statamic migration, and improving user experience. These case studies provide a glimpse into how we tailor our technology choices to meet specific client needs and deliver exceptional results.

Heading Pattern

Related Posts

Stay up to date

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