oliverbusk
5 months ago
120
6
Laravel

Web controllers and API controllers

Posted 5 months ago by oliverbusk

Hi all!

So I've found myself stuck in my thoughts... Consider below resource controller:

DocumentsController.php

public function index(){}

public function show(){}

public function store(){}

public function destroy(){}

Which is used to serve the views for the frontend.

Now this works fine. I can perform the basic CRUD actions for the Documents.

However in my app, I have created a new Vue file called

DocumentViewer.vue, that will be used to show specific documents, that belongs to specific users/other parameters.

I would like to fetch the documents by using Laravel/Vue and a simple AJAX call to the backend. Something like:

data() {
     return {
         documents: []
     }
},
created() {
   axios.get("/documents/userDocuments")
             .then(response => this.documents = response.data);
}

As you can see, I have specified a URL called /documents/userDocuments, which may be referenced in the routes/api.php file like:

Route::group([
   'prefix' => 'api',
   'middleware' => 'auth:api'
], function() {

   Route::get("documents/userDocuments", [email protected]);    

});

This is my initial thoughts. However, for some reason it feels a bit.. "non-Laravel" like, and I am not sure if it goes against best practices.

My concerns are:

  1. I have my normal controller CRUD resource endpoints defined inside my routes/web.php file. Would it be OK to place the endpoint for the Vue endpoints within the routes/api.php file - or should this be placed within the web.php file?

  2. I'm a bit unsure about naming conventions in above. I'm referring to getUserDocuments, which will be a function within my DocumentsController - but this goes a bit against the clean controller structure. But on the other side, creating a new controller doesn't seem right either?

Please sign in or create an account to participate in this conversation.