StackOverflowNewbie
StackOverflowNewbie

Reputation: 40633

Laravel Routes - how to "mod rewrite"?

I'm developing an API. Say I have the following endpoints that should output the same resources:

  1. /api/users/5/comments
  2. /api/comments?user-id=5

I have a controller to handle the users endpoint, and I have a controller to handle the comments endpoint. Each controller also handles all the filtering, sorting, etc. required.

Since the two endpoints provided should output the same data, is there a way I can tell Laravel that in routes? I don't want to use the implementation of #2 URL above to also output the appropriate response for #1 URL.

I guess I'm looking for something akin to MOD REWRITE in .htaccess.

Upvotes: 1

Views: 108

Answers (1)

mrhn
mrhn

Reputation: 18916

Wouldn't pointing to the same controller suffice?

Route::get('/api/users/{userid}/comments', 'CommentController@index');
Route::get('/api/comments', 'CommentController@index');

Then handling the specific case if it has user-id provided.

public function index(Request $request) {
    $commentQuery = Comment::query();

    $commentQuery->when($request->query->has('user-id'), function ($query) use ($request) {
        $query->where('user-id', $request->query->get('user-id'));
    });

    return $commentQuery->get();
}

Upvotes: 1

Related Questions