Open In App

Laravel | Route::resource vs Route::controller

Improve
Improve
Like Article
Like
Save
Share
Report

In Laravel, the Route actions can be controlled by any of the following two methods, either by using Route::resource method or by using Route::controller method. But both of them have their differences. Route::resource: The Route::resource method is a RESTful Controller that generates all the basic routes required for an application and can be easily handled using the controller class. It takes two arguments, where first is the base incoming request URI (Uniform Resource Identifier) and second is the class name of the controller which is used to handle the request. With this method, we get route names and path defined by default with 7 different actions which are required for any application. Note: To get the list of routes created, we have to use the command ‘PHP artisan route: list’ in the command line. Example:

  • routes.php
Route::resource(‘gfg’, ‘GeeksforGeeksController’);
  • Output:

Route::controller: The Route::controller method is an Implicit Controller which also takes two arguments and are same as Route::resource method i.e. first is the base incoming request URI (Uniform Resource Identifier) and second is the class name of the controller which is used to handle the request. With this method, we have a little flexibility in how we define our route names. There are no route names defined by default as there were with Route::resource method. Note: To get the list of routes created, you have to use the command ‘PHP artisan route: list’ in the command line. Example:

  • routes.php:
Route::controller(‘gfg’, ‘GeeksforGeeksController’);
  • GeeksforGeeksController.php: When no method is defined in the controller class file, then we get the output as shown below:
class GeeksforGeeksController extends Controller
{
  // Handle request
}
  • Output:
  • GeeksforGeeksController.php: When we define get and post method in the controller class file, then we get the output as shown below.
class GeeksforGeeksController extends Controller
{
  public function getGeek()
  {
    // Handle get request
  }
  public function postGeek($id)
  {
    // Handle post request
  }
}
  • Output:

Before specifying either of the routes, you have to create the controller class which you want to use in the route. You can do that using a simple artisan command that is ‘PHP artisan make: controller GeeksforGeeksController’ i.e. ‘PHP artisan make: controller ’. The Route:Controller method had its support till Laravel 5.1 and is no longer supported by the versions after that. So, in the later versions of Laravel, we use Route::resource method.


Last Updated : 18 Apr, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads