Laravel Basic Controllers

Controllers group relate request handling logic into a single class. They are stored in the app/Http/Controllers directory.

Basic Controllers

Defining Controllers:

The controllers extend the base controller class included with Laravel.

The base class provides a few uses to obtain methods such as the middleware method, which we used to attach the middleware to controller actions:

<?php
 namespace App\Http\Controllers;
 use App\User;
 use App\Http\Controllers\Controller; 
 class UserController extends Controller
 {
     /**
      * Show the profile for the given user.
      * 
      * @param  int  $id
      * @return View
      */
     public function show($id)
     { 
         return view('user.profile', ['user' => User::findOrFail($id)]);
     }
 } 

We can easily define a route to this controller:

Route::get(‘user/{id},’ ‘UserController@show’);

Now, when a request matches the specified route URI, the show method on the UserController class will be executed.

The route parameters will also be passed with this method.

  • Controllers are not required to extend a base class. On the other hand, we will not have access to convenience features such as the middleware, validate, and dispatch methods.

Controllers & Namespaces:

We did not need to specify the full controller namespace while defining the controller route.

The RouteServiceProvider loads our route files within a route group which contains the namespace, we can specify the portion of the class name that comes after the App\Http\Controllers portion of the namespace.

If we choose to divide our Controllers into the App\Http\Controllers directory, it uses the specific class name that is related to the App\Http\Controllers root namespace.

If our full controller class is App\Http\Controllers\Photos\AdminController, we should register routes to the controller like so:

Route::get(‘foo’, ‘Phots\AdminController@method’);

Single Action Controllers:

If we would like to define a controller that are only handles a single action, we place a single _invoke method on the controller:

<?php
 namespace App\Http\Controllers;
 use App\User;
 use App\Http\Controllers\Controller;
 class ShowProfile extends Controller 
 {
 /**
 * Show the profile for the given user. 
 *
 * @param  int  $id
 * @return View
 */ 
 public function __invoke($id)
 {
 return view('user.profile', ['user' => User::findOrFail($id)]); 
 }
 } 

When we are registering routes for a single action controllers, we do not need to specify a method:

Route::get('user/{id}', 'ShowProfile');

We can generate an invokable controller by using the --invokable option of the make:controller Artisian command:

php artisian make:controller ShowProfile --invokable