Search code examples
laravelstringlaravel-8

Str is working without import facade in laravel 8


I am using str class in my helpers like below without import facade it is working fine without throwing any error. I am feeling little strange how it is working can any one explain.

if(!function_exists('testHelper')){
    function testHelper($string){
        $numbers = Str::replace(['(',')','-',' '],'',$string);
        return $numbers;
    }
}

if no need to import facade explicitly for str class ,how come it is working in which file it is bootstraped.Thanks in advnace !!


Solution

  • Laravel's Facade and some classes are registered as an alias.
    It can be used without importing only in the global scope.
    Blade view, config file, custom helpers, etc.

    // blade
    {{ Str::replace() }}
    
    // controller
    use Illuminate\Support\Str;
    Str::replace();
    
    // or (not recommended)
    \Str::replace();
    

    https://github.com/laravel/framework/blob/11.x/src/Illuminate/Foundation/AliasLoader.php

    https://www.php.net/manual/en/function.class-alias.php