Namespaces in Laravel

Namespaces in Laravel are defined as a class of elements in which each element has a different name to that associated class. The use keyword allows us to shorten the namespace. Actually, it is pretty easy to use namespaces.

For example,

namespace App\Models;

 

class File {

 

    public function TheMethodThatGetsFiles()

    {

 

    }

}

In the controllers, we are using namespace.

app/controllers/FileController.php

namespace App\Controllers;

 

use App\Models\File;

 

class FileController {

 

    public function someMethod()

    {

 

        $file = new File();

    }

}

When you put a class in a name space to access any of the built in classes that you need to call from Root Namespace. i.e.   $stdClass = new stdClass(); becomes $stdClass = new \stdClass();

To import other namespaces:

use App\Models\File;

This will allow you to use File class without Namespace prefix.

You have to put the namespace at the top for easily understanding the file’s dependencies. After that run composer dump-autoload. If you want to access FileController then you will need to define route and specify the full namespace which will redirect it to the specified method of the controller.

Route::get('file', 'App\\Controllers\\FileController@TheMethod');