Home > Software engineering >  Refactor Query Builder Laravel
Refactor Query Builder Laravel

Time:04-30

I want to do repetitive get data and foreach on several tables (see example below). Is there a way to write the code in a cleaner way instead of repeating the same code for all the tables?

$xs = DB::table('table1')->where('text', 'like', '%string')->get();

foreach ($xs as $x) {
           ..
}

$ys = DB::table('table2')->where('text', 'like', '%string')->get();

foreach ($ys as $y) {
           ..
}```

CodePudding user response:

My approach is using array and foreach

$tables = ['table1', 'table2'];
results = [];

foreach($tables as $table) {
  $data = DB::table($table)->where('text', 'like', '%string')->get();
  foreach($data as $d) {
    // your logic here
  }
  $results[] = ; // return a value from each query to array
}

CodePudding user response:

You can write a base function and pass tableName to it and execute certain action

public function getData($tableName) {
  $query = DB::table($tableName)->where('text', 'like', '%string')->get();
  foreach ($query as $row) {
          ...
   }

  // return result;
}

$tables = ['table1', 'table2', 'table3'];
$queryResponse = [];

foreach($tables as $tableName) {
    $queryResponse[$tableName] =  $this->getData($tableName);
}
  • Related