php - How to prevent duplicate code in laravel?

I Have a model called HttpLogModel.I insert response and request and duration in Httplogs table after any http request client. I have used this code in different places.

  $startTime = microtime(true);

  // this part is dynamic code 
  $client =  Http::get($url); 
  //Or
  $client = Http::get($url, ['name' => 'Taylor','page' => 1,]); 
  //Or 
  $client = Http::asForm()->post($url, ['name' => 'Taylor','page' => 1,]); 
  /// Or any http client request

  $durationTime = microtime(true) - $startTime;

  if ($client->clientError() || $client->serverError()) {
      HttpLogModel::addErrorLog(
        $provider, $step, $data, $client->toException()->getMessage(), $url, $durationTime
     );

     if ($client->status() == 401) {
        throw new InvalidTokenException();
     }

     if ($client->serverError()) {
        throw new ServerException();
     }

     throw new ProviderException('ProviderException');
  }

   HttpLogModel::addLog(
      $provider, $step, $client, $url, $durationTime
   );

   return $client->json();
  }

How to prevent duplicate code?

Answer

Solution:

I'd suggest looking into repository pattern. What it basically is, it's a class, in a different Namespace, where you inject the model and create all sorts of functions using the model inside of it.

The trick is that each time you need a certain query, you use the repository and each time you tend to duplicate, you put the queries in the repository and use it that way.

For that I recommend you:https://asperbrothers.com/blog/implement-repository-pattern-in-laravel/ I encourage you to try it. It sounds fancy but it is nothing more than another class.

If you find it confusing, you have another solution.

Take that query that you have duplicated and put it into a static method. For example, lets say you have the following class:

Class SomeModel extends Model {

}

and you query it in different places like this:

$someCollection = SomeModel::Where('column', $value)->where('other_column', $otherValue)->get();

For example you can use this into a controller but then need it into a command and find yourself duplicating it. Now, you can go to that class

Class SomeModel extends Model {

}

add

public static function something() {
    return SomeModel::Where('column', $value)->where('other_column', $otherValue)->get();
}

and then go in each place you have use it and replace it with

SomeModel::something();

Source