skip to Main Content

I want to know Is it possible to utilize Laravel Facades without importing them to scope by ‘use’ statement?

//use IlluminateSupportFacadesRoute;
use IlluminateHttpRequest;
//use IlluminateSupportFacadesCookie;


Route::get('/home',function(Request $request){
    Cookie::queue('userIp',$request->ip(),2);
        return view('home');
});

I tried it and it worked!(Laravel 10.x)
Cookie and Route facades worked without importing them to web.php file!

2

Answers


  1. Chosen as BEST ANSWER

    All alias names are kept in an aliases array inside the app.php config file, which is located inside the /config directory.

    If we take a look at the array, we can see that each alias name is mapped to a fully-qualified class name. This means we can use any name that we wish for a facade class: Okay, now let’s see how Laravel uses this array for aliasing the facade classes. In the bootstrapping phase, Laravel uses a service named AliasLoader which is part of the IlluminateFoundation package. AliasLoader takes the aliases array, iterates over all the elements, and creates a queue of __autoload functions using PHP’s spl_autoload_register. Each __autoload function is responsible for creating an alias for the respective facade class by using PHP’s class_alias function.

    As a result, we won’t have to import and alias the classes before using them as we normally do with the use directive. www.sitepoint.com


  2. You can use the helpers or Dependency Injection of that facade I recommend checking docs about what are the diffs.

    You have Dependency Injection when in the class you "inject" via the constructor, laravel does it a lot, you can check more on docs.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search