Routing is a mechanism that Laravel uses to decide which method is to be executed when a request is made to a controller class. A large application could have lots of request-handling logic defined. Storing these in a single file could make the code hard to maintain.
It is usually better to keep the code for all of this logic organized by making use of Controller classes. These are stored in the App/Http/Controllers directory.
A default Laravel installation has a base controller that controls other controllers. So, all controllers should extend the default controller. The code below is an example of what a basic controller in Laravel might look like:
<?php namespace App\Http\Controllers; use App\User; use App\Http\Controllers\Controller; class ProfileController extends Controller { /** * Show the profile for the given user. * * @param int $id * @return Response */ public function displayProfile($id) { return view('user.profile', ['user' => User::findOrFail($id)]); } }
To route the controller action above, use the following line of code:
Route::get('user/{id}', 'ProfileController@displayProfile');
When a request is made and it matches the URI in the specified route, the displayProfile method of the ProfileController class will be executed. The route parameters will also be passed to the method.
Controllers In Laravel: Namespaces
In the code above, we did not need to specify the full controller namespace when defining the route of the controller. What we did was to define the portion of the class name that follows App/Http/Controllers.
If you decide to create your controllers in a sub-directory of App/Http/Controllers use a class name that is relative to that directory. You don’t have to use the absolute path of the controller.
So, if your controller class is stored at App\Http\Controllers\Photos\DahsboardController for example, the route should be registered like this:
Route::get('foo', 'Photos\DashboardController@method');
Single Action Controllers
Sometimes, you may want to create a controller that handles just a single action. To do this, place a single __invoke method in the controller like this:
<?php namespace App\Http\Controllers; use App\User; use App\Http\Controllers\Controller; class DisplayProfile extends Controller { /** * Show the profile for the specified user * * @param int $id * @return Response */ public function __invoke($id) { return view('user.profile', ['user' => User::findOrFail($id)]); } }
When registering routes for single action controllers, you do not need to specify the method you want to work with. Here’s an example:
Route::get('user/{id}', DisplayProfile');
That’s it.
This is a primer on controllers in Laravel. I’ll gladly entertain questions on this topic if you have any. You can leave your comments and questions using the comments box below.
If you desire even more details, check out the official Laravel controllers documentation.
Leave a Reply