Autoload class alias order in Laravel tinker

Posted on 12. Juli 2021 Comments

When using tinker or tinkerwell without use statements or FQCN it tries to guess which class you mean by going through the autoloaded classes alphabetically. This might not be the class you most often used though, e.g. it is more likely I’d like to use App\Models\User, not the Livewire component of the same name.

$ tinker
UserPsy Shell v0.10.8 (PHP 8.0.8 — cli) by Justin Hileman
>>> User::first()
[!] Aliasing 'User' to 'App\Http\Livewire\User' for this Tinker session.

PHP provides the class_alias function but e.g. writing your own Service Provider for this will not work.

class ClassAliasesProvider extends ServiceProvider
{
    /**
     * Class Aliases defaults for tinker / tinkerwell.dev
     *
     * @return void
     */
    public function boot()
    {
        class_alias(User::class, 'User');
        //
    }
}

Instead, add your classes to the array in config(‚app.alias‘).

        // other default Laravel aliases
        'View' => Illuminate\Support\Facades\View::class,

        // Better autoloading for tinker / tinkerwell
        'User' => \App\Models\User::class,

The next time loading up tinker / tinkerwell, it will use the correct alias.

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert

Diese Website verwendet Akismet, um Spam zu reduzieren. Erfahre mehr darüber, wie deine Kommentardaten verarbeitet werden.