I'm learning Laravel, and in a project I've seen that inside a controller they don't put the full path in the use and shorten it.
use Auth;
use Validator;
use App\User;
Why does this work?
I'm learning Laravel, and in a project I've seen that inside a controller they don't put the full path in the use and shorten it.
use Auth;
use Validator;
use App\User;
Why does this work?
You don't put the full path if the class is in the same namespace. For controllers usually the namespace is
App\Http\Controllers
.So for your example,
Auth
andValidator
would have to be in the same namespace as the controller where you're using them (App\Http\Controllers
) for them to work. But this is not the case, because Auth and Validator are classes ofIlluminate\Support\Facades
, so they must have an alias defined inconfig/app.php
so as not to have to put the entire namespace, something like that'Auth' => Illuminate\Support\Facades\Auth::class,
and the same forValidator
.You can see
config/app.php
inside the arrayaliases
if they are there.Instead
User
, which is surely a model, has another namespace. So you put the namespace and the class:App\User
.They are the namespace where the classes you require are located
For example , it
App\User
indicates the main namespace isApp
the one that points to the folderapp
and inside it looks for a model calledUser
whose class is called in the same wayThis is not only a Laravel issue but in PHP it can be done with the PSR-4 implementation, for automatic class loading you avoid the use of
requiere
or similar functionsFor example, by making use of use
App\User
you will have the imported classUser
and therefore access to its methods and propertiesIf you check each
namespace
, it refers to the folder path within which the resource we want to reach is located.Then the classes
Auth
andValidator
exist inside the folder, that'sControllers
why it only imports them by name because they exist at the same level as the controller that uses them.