1

Let's say I want to make a RESTful API for external devices such as Android, and at the same time I want to consume this API using web routes and Blade templates.

Route: api/articles/{id}/edit

public function API_edit(Article $article)
{
    $article->body = request('body');
    $article->save();

    return response()->json([...]);
}

Now here's the thing. What should I do in order to not repeat myself? Because I guess it's not OK to create another method that basically does the same as API_edit.

Route: articles/{id}/edit

public function edit(Article $article)
{
    $article->body = request('body');
    $article->save();

    return redirect()->back()->with(['message' => 'Article edited']);
}

This must be wrong, it's a simple example but what if the logic is more complex? It doesn't feel right.

bruno-alod
  • 27
  • 1
  • 4
  • Why not calling edit from API_edit, creating a parameter in the edit method saying if it has to return a view or JSON data ? – David Alvarez Feb 22 '20 at 21:13

3 Answers3

0

In this case that's probably exactly what you should do. As you say, the logic could be more complex, in which case you probably shouldn't leave it in your controller regardless of re-use across web/api routes. If there's any complexity to the action your controller need to perform extract it to a service of some kind.

Calum Halpin
  • 1,945
  • 1
  • 10
  • 20
0

You can use wantsJson method of \Illuminate\Support\Facades\Request facade to check:

public function edit(Article $article)
{
    $article->body = request('body');
    $article->save();
    $response = ['message' => 'Article edited'];

    if (Request::wantsJson()) {
        return response()->json($response);
    }

    return redirect()->back()->with($response);
}
Ruben Danielyan
  • 728
  • 4
  • 19
0

Take a look at this post, if I understand your question correctly (Laravel Web and API controller structure. Separate vs DRY).

You will need to set up and "duplicate' the routes for both when being used within a RESTful API for an external framework like Vue/Angular or any external service, and have those routes getting handled internally inside the web.php too to handle the internal request.

However, you can still point these requests to the same controller.

Like the following:

web.php

Route::get('/some/web/request', 'YourController@function')

api.php

Route::get('/some/api/request', 'YourController@function');
Tanner
  • 720
  • 1
  • 8
  • 17