jdawg
jdawg

Reputation: 558

Laravel Route Controller

I have a working solution within routes.php, but I understand that laravel can handle restful routes better. I've tried using their documentation to implement restful resource controllers, but had no luck.

This is what I have at the moment

Route::get('/invoices', 'InvoicesController@showInvoices');
Route::get('/invoices/data', 'InvoicesController@getInvoices');

Basically, the showInvoices returns the invoices view and getInvoices returns a JSON string for DataTables which is called from the invoices view.

So I want to be able to call /invoices to get the view and then call /invoices/data using JavaScript.

Any suggestions how to convert this to a resource controller or more suitable controller?

Upvotes: 1

Views: 482

Answers (2)

idelara
idelara

Reputation: 1816

You could create a "resource" route like so:

Route::resource('/invoices', 'InvoicesController');

Which will provide RESTful routes (GET, POST, PUT, etc...) for that particular /invoices route/resource. You can check this by executing php artisan route:list

You can learn more here.

I hope this helped.

Cheers!

Upvotes: 0

Milan
Milan

Reputation: 759

Yes, there was a cleaner way. Route controllers were supported up to Laravel 5.3. Then this functionality was removed in favor of explicit routes, which leave the routes files in disarray when you have lots of routes.

Fortunately, there is a class I wrote called AdvancedRoute, which serves as a drop in replacement.

In your case you can use it like this:

Route::get('/invoices', 'InvoicesController@showInvoices');
Route::get('/invoices/data', 'InvoicesController@getInvoices');

Becomes:

AdvancedRoute::controller('/invoices', 'InvoicesController');

Explicit routes are built automatically for you. Have in mind you have to follow a convention by prefixing the method names with the request method, which I personally find very clean and developer friendly:

InvoicesController@getInvoices => /invoices
InvoicesController@getInvoicesData => /invoices/data

Full information how to install and use find at the GitHub repo at:

https://github.com/lesichkovm/laravel-advanced-route

Hope you find this useful.

Upvotes: 1

Related Questions