instead of defining all of your request handling logic in a single routes.php
file, you may wish to organize this behavior using Controller classes. Controllers can group related HTTP request handling logic into a class. Controllers are typically stored in the app/Http/Controllers
directory.
Here is an example of a basic controller class:
<?php namespace App\\Http\\Controllers;
use App\\Http\\Controllers\\Controller;
class UserController extends Controller {
/**
* Show the profile for the given user.
*
* @param int $id
* @return Response
*/
public function showProfile($id)
{
return view(\'user.profile\', [\'user\' => User::findOrFail($id)]);
}
}
We can route to the controller action like so:
Route::get(\'user/{id}\', \'UserController@showProfile\');
Note: All controllers should extend the base controller class.
It is very important to note that we did not need to specify the full controller namespace, only the portion of the class name that comes after the App\\Http\\Controllers
namespace \"root\". By default, the RouteServiceProvider
will load the routes.php
file within a route group containing the root controller namespace.
If you choose to nest or organize your controllers using PHP namespaces deeper into the App\\Http\\Controllers
directory, simply use the specific class name relative to the App\\Http\\Controllers
root namespace. So, if your full controller class is App\\Http\\Controllers\\Photos\\AdminController
, you would register a route like so:
Route::get(\'foo\', \'Photos\\AdminController@method\');
Like Closure routes, you may specify names on controller routes:
Route::get(\'foo\', [\'uses\' => \'FooController@method\', \'as\' => \'name\']);
To generate a URL to a controller action, use the action
helper method:
$url = action(\'App\\Http\\Controllers\\FooController@method\');
If you wish to generate a URL to a controller action while using only the portion of the class name relative to your controller namespace, register the root controller namespace with the URL generator:
URL::setRootControllerNamespace(\'App\\Http\\Controllers\');
$url = action(\'FooController@method\');
You may access the name of the controller action being run using the currentRouteAction
method:
$action = Route::currentRouteAction();