A class of items with distinct names for each member of the related class is known as a namespace. It might be shared with other classes’ elements.

Understanding Namespaces in Laravel

Declaring Namespaces

Namespaces can be shortened with the use keyword for better code readability.

use <namespace-name>;

Although App is the namespace that Laravel uses by default, a user can modify it to match a web application. The following describes how to use the artisan command to create a user-defined namespace:

php artisan app:name SocialNet

Namespaces serve as containers for functionalities, enabling their utilization within controllers and other classes.

Laravel Controllers: Handling Requests

Enter the following command to build a controller using the Artisan CLI (Command Line Interface) on the command prompt or terminal, depending on the operating system you are using.

php artisan make:controller <controller-name> --plain

Put your controller’s name in place of . Since we are supplying the argument plain, this will result in a plain constructor. You can disregard the argument if you don’t want to write a simple constructor. You can view the constructed constructor under app/Http/Controllers.

You can add your own custom coding after you notice that some basic coding has already been completed for you. The following syntax can be used to invoke the generated controller from routes.php.

Syntax

Route::get(‘base URI’,’controller@method’);

Example

Step 1: The following command will generate the UserController class:

php artisan make:controller UserController --plain

Step 2: The following output is expected upon successful completion:

Step 3: he newly created UserController is located at app/Http/Controllers/UserController.php. This file contains some starter code; you can add to it as required.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class UserController extends Controller {
   //
}

Applying Middleware to Controllers

We have already seen middleware, which can also be utilized with controllers. Additionally, middleware can be included in your controller’s constructor or allocated to the controller’s route. Assigning middleware to the controller can be done via the middleware method. Additionally, the registered middleware may be limited to a specific controller method.

Route-Based Middleware Assignment

Route::get('profile', [
   'middleware' => 'auth',
   'uses' => 'UserController@showProfile'
]);

The profile route within UserController is configured to utilize the auth middleware.

 Middleware Assignment within the Controller’s Constructor Method

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class UserController extends Controller {
   public function __construct() {
      $this->middleware('auth');
   }
}

The auth middleware is applied to the UserController through invocation of the middleware method within its constructor.

Example

Step 1: In app/Http/routes.php, add the following code, then save the file.

routes.php

<?php
Route::get('/usercontroller/path',[
   'middleware' => 'First',
   'uses' => 'UserController@showPath'
]);

Step 2: Generate the FirstMiddleware middleware using this command:

php artisan make:middleware FirstMiddleware

Step 3: Insert the following code within the handle method of the FirstMiddleware class, located at app/Http/Middleware/FirstMiddleware.php

FirstMiddleware.php

<?php

namespace App\Http\Middleware;
use Closure;

class FirstMiddleware {
   public function handle($request, Closure $next) {
      echo '<br>First Middleware';
      return $next($request);
   }
}

Step 4: The following command will generate the SecondMiddleware middleware.

php artisan make:middleware SecondMiddleware

Step 5: In the handle method of the newly created SecondMiddleware (located at app/Http/Middleware), add the following code

<?php

namespace App\Http\Middleware;
use Closure;

class SecondMiddleware {
   public function handle($request, Closure $next) {
      echo '<br>Second Middleware';
      return $next($request);
   }
}

Step 6: The following command will generate the UserController controller class:

php artisan make:controller UserController --plain

Step 7: Insert the following code into the app/Http/Controllers/UserController.php file

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class UserController extends Controller {
   public function __construct() {
      $this->middleware('Second');
   }
   public function showPath(Request $request) {
      $uri = $request->path();
      echo '<br>URI: '.$uri;
      
      $url = $request->url();
      echo '<br>';
      
      echo 'URL: '.$url;
      $method = $request->method();
      echo '<br>';
      
      echo 'Method: '.$method;
   }
}

Step 8: Initiate the PHP internal web server by executing the following command, provided it is not currently active:

php artisan serve

Step 9: Please navigate to the following URL:

http://localhost:8000/usercontroller/path

Step 11: The anticipated output is depicted in the following image.\

Controllers for RESTful Resources

CRUD (Create, Read, Update, Delete) actions are frequently required while creating an application. This task is made simple for us by Laravel. Laravel will automatically supply all of the methods for the CRUD tasks if you simply create a controller. In the routes.php file, you can additionally register a single route for each method.

Example

Step 1: Use this command to create the MyController:

php artisan make:controller MyController

Step 2: Append the following code to the app/Http/Controllers/MyController.php file:
app/Http/Controllers/MyController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class MyController extends Controller {
   public function index() {
      echo 'index';
   }
   public function create() {
      echo 'create';
   }
   public function store(Request $request) {
      echo 'store';
   }
   public function show($id) {
      echo 'show';
   }
   public function edit($id) {
      echo 'edit';
   }
   public function update(Request $request, $id) {
      echo 'update';
   }
   public function destroy($id) {
      echo 'destroy';
   }
}

Step 3: Append the following line of code to the routes/web.php file:

Route::resource('my','MyController');

Step 4: The MyController class has been registered as a resource controller, automatically exposing all its methods via RESTful routes. The table below provides a mapping of HTTP actions to the corresponding controller methods:

VerbPathActionRoute Name
GET/myindexmy.index
GET/my/createcreate my.create
POST/mystore my.store
GET/my/{my}showmy.show
GET/my/{my}/editeditmy.edit
PUT/PATCH/my/{my}updatemy.update
DELETE/my/{my}destroymy.destroy

Step 5: Please attempt to access the URLs specified in the following table:

Implicit Controller Instantiation

With implicit controllers, you may specify a single path to manage each controller action. As seen below, you may define it in the route.php file using the Route:controller method.

Route::controller(‘base URI’,’<class-name-of-the-controller>’);

Put the class name you assigned to your controller in place of <class-name-of-the-controller>.

The controller’s method name should begin with an HTTP verb, such as get or post. It will only handle get requests if you start it with “get,” and it will handle post requests if you start it with “post.” You can name the method anything you like after the HTTP verb, but it must use the URI’s title case.

Example

Step 1: To construct a controller, use the command below. The class name ImplicitController has been retained. You are free to give the class any name you like.

php artisan make:controller ImplicitController --plain

Step 2: Upon successful completion of step 1, the following output is expected.

Step 3: Insert the following code into the app/Http/Controllers/ImplicitController.php file:

app/Http/Controllers/ImplicitController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class ImplicitController extends Controller {
   /**
      * Responds to requests to GET /test
   */
   public function getIndex() {
      echo 'index method';
   }
   
   /**
      * Responds to requests to GET /test/show/1
   */
   public function getShow($id) {
      echo 'show method';
   }
   
   /**
      * Responds to requests to GET /test/admin-profile
   */
   public function getAdminProfile() {
      echo 'admin profile method';
   }
   
   /**
      * Responds to requests to POST /test/profile
   */
   public function postProfile() {
      echo 'profile method';
   }
}

Step 4: The following route definition, added to routes/web.php, will direct requests to the specified controller.

app/Http/routes.php

Route::controller('test','ImplicitController');

Injecting Constructors

All Laravel controllers are resolved using the Laravel service container. This means that you can type-hint any dependencies that your controller might require in its constructor. The controller instance will automatically resolve and inject the dependencies.

Example

Step 1: Append the following route definition to the routes/web.php file:

app/Http/routes.php

class MyClass{
   public $foo = 'bar';
}
Route::get('/myclass','ImplicitController@index');

Step 2: Paste the following code into app/Http/Controllers/ImplicitController.php

app/Http/Controllers/ImplicitController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class ImplicitController extends Controller {
   private $myclass;
   
   public function __construct(\MyClass $myclass) {
      $this->myclass = $myclass;
   }
   public function index() {
      dd($this->myclass);
   }
}

Step 3: Please navigate to the following URL to verify constructor injection functionality.

http://localhost:8000/myclass

Step 4: The anticipated output is depicted below:

 Injecting dependencies into methods

Controller action methods support dependency injection via type hinting, in addition to constructor injection.

Example

Step 1: Paste the following code into your routes/web.php file:

app/Http/routes.php

class MyClass{
   public $foo = 'bar';
}
Route::get('/myclass','ImplicitController@index');

Step 2: Paste the following code into app/Http/Controllers/ImplicitController.php

app/Http/Controllers/ImplicitController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class ImplicitController extends Controller {
   public function index(\MyClass $myclass) {
      dd($myclass);
   }
} 

Step 3: Please navigate to the following URL to verify constructor injection functionality:

http://localhost:8000/myclasshttp://localhost:8000/myclass

You should see this output:

Categorized in: