Laravel - Namespaces

Namespaces are used in various programming languages to create a separate group of variable, functions and classes. A program may contain various functions and this may result in conflict with existing functions.

Declaration of namespace

Namespaces can be defined as a class of elements in which each element has a unique name to that associated class. It may be shared with elements in other classes.

You can declare a namespace as shown in the syntax given below −

use <namespace-name>;

Please note that the use keyword allows the developers to shorten the namespace. The default namespace used in Laravel is app, however a user can change the namespace to match with a web application.

You can create a user defined namespace by using artisan command as shown below −

On giving the above command, you can observe the output as shown in the following screenshot − The namespace once created can include various functionalities which can be used in controllers and various classes. The code created on the basis of namespace in controller and kernel with files namely app/console/kernel.php and app/Http/controller.php are shown below



namespace Tutorialspoint\Console;

use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;

class Kernel extends ConsoleKernel{
      * The Artisan commands provided by your application.
      * @var array
   protected $commands = [
      * Define the application's command schedule.
      * @param \Illuminate\Console\Scheduling\Schedule $schedule
      * @return void
   protected function schedule(Schedule $schedule){
      // $schedule->command('inspire')
      // ->hourly();
      * Register the Closure based commands for the application.
      * @return void
   protected function commands(){
      require base_path('routes/console.php');

Note that the functions namely schedule and commands helps in scheduling methods for Cron jobs and other functionalities.


namespace Tutorialspoint\Http\Controllers;

use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;

class Controller extends BaseController{
   use AuthorizesRequests, DispatchesJobs, ValidatesRequests;

The controllers act as an intermediary between models and views. For the namespace which we created called Tutorialspoint, they will be used in core file of controllers controller.php. The namespace is initialized properly with Http\Controllers.

The namespace once created uses various other namespaces like AuthorizesRequests, DispatchesJobs and ValidatesRequests as mentioned in the above code.