Reputation: 6907
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
Upvotes: 4
Views: 1525
Reputation: 6511
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.
Upvotes: 0
Reputation: 87719
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 {
}
Upvotes: 1