Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

untymage's avatar

Using external API to create record directly but DRY way

I have two way to create a record (Movie post) One is manually with html form another one is with external APIs, Both have separated controllers, But one thing that bothers me is How to avoid duplicates ? For example i validates data which come from html form and the other hand the data comes from external APIs, So my questions:

  1. How to validates data that come from external API (DRY way)
  2. How to forward external api data to antother controller to avoid duplicates

From html:

public function store(MovieRequest $request)
{
    Movie::create([
        'title' => $request->title,
        'year'  => $request->year,
    ]);
    // ...
}

from APIs:

public function store(Request $request)
{
    
    $client = new GuzzleHttp\Client();
    $res = $client->get($request('apiURL'))->getBody();
    
    How to pass $res to above controller to avoid duplicates and valdiation here ?
    

}
0 likes
2 replies
kingshark's avatar

You can:

  • fetch the data from external api
  • build a request instance $req manually
  • call another controller's method using return app('App\Http\Controllers\Html\MovieController')->store($req);.

But I won't recommend this approach. I'd rather write store function's main logic in a extra layer such as repository or service, then for both Controllers, call this service's method.

1 like
Tray2's avatar

I would probably use the same controller for both the "html" and the "api" way since they are the same.

Something like

public function store(Request $request)
{
    $movie = Movie::create($this->validate($request));
    $message = $movie->title . ' Successfully added';
    if($request->wantJson()) {
        return response()->json([
                'status => 200,
                'message' =>  $message
        ]);
        return redirect('/movies')->with(['message' => $message]);
}
1 like

Please or to participate in this conversation.