4

I am creating an API and I want to include both regular resources and nested resources

For example, I will say I have a Post resource and Comment resource. I have setup the appropriate routes and controllers like the following

Routes

Route::resource('posts', 'PostsControllers'); // /posts/{id}
Route::resource('comments', 'CommentsControllers'); /comments/{id}

But I also want to have comments as a nested resource of posts, like this

Nested resource route

Route::resource('posts.comments', 'PostCommentsControllers'); /posts/{id}/comments/{id}

Because I have already written my CommentsController, I would like to know of the best method to re-use the CommentsController for my PostsController

Thanks

0

2 Answers 2

1

Using inheritance is the best way:

class BaseController extends Controller {

    public function index() {

    }   

    public function create() {

    }       

    public function store() {

    }       

    public function update() {

    }       

}

class PostsController extends BaseController {

}

class CommentsController extends BaseController {

}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the answer. I figured that extend a base class. An issue I saw is for example with the store() method. For the parent resource the signature would look like this: store($id) but in the nested resource it would look like: store($parent_id, $id) but that majority of the logic would be the same
0

You can just extend your Blog/Comment/*Controller on a generic FooBarController which holds all the logic.

You will have to supply the model and other model-related data, I do this via the constructor, and my models holding data about the columns, etc.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.