微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Laravel:auth()->尝试未定义的方法

如何解决Laravel:auth()->尝试未定义的方法

似乎一切正常,但 VSCODE 在尝试时不断报告错误。说方法还没有定义。

<?PHP

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;

class RegisterController extends Controller
{
    public function index()
    {
        return view('auth.register');
    }

    public function store(Request $request)
    {
        //validation
        $this->validate($request,[
            'name' => 'required|max:50','username' => 'required|max:50','email' => 'required|email|max:250','password' => 'required|confirmed',]);
        //create new user
        User::create([
            'name' => $request->name,'username' => $request->username,'email' => $request->email,'password' => Hash::make($request->password),]);

        auth()->attempt($request->only('email','password'));

        return redirect()->route('dashboard');

        //sign the user in
        //redirect
    }
}

是 vscode 的问题还是我遗漏了什么?

解决方法

这是我解决的:

打开扩展设置:

enter image description here

并打开设置的json

enter image description here

您应该考虑的变量是:

"intelephense.diagnostics.undefinedTypes": false,"intelephense.diagnostics.undefinedFunctions": false,"intelephense.diagnostics.undefinedConstants": false,"intelephense.diagnostics.undefinedClassConstants": false,"intelephense.diagnostics.undefinedMethods": false,"intelephense.diagnostics.undefinedProperties": false,"intelephense.diagnostics.undefinedVariables": false,

然后按 control + shift+p 并搜索 intelephense 然后选择 index worksapce

,

所以我想我关注了同一个 tutorial of TraversyMedia 的客人亚历克斯,并偶然发现了同样的问题。

虽然抑制诊断显然有效,但这并不是我想要的(不接受)。

在这种情况下,方法 attempt 存在,所以我只希望很棒的 Intelephense 扩展能够识别它。

我会试着解释一下,所以它不仅仅适用于这种情况。

解决方案

Ctrl + click on auth() 应该有方法将我们带到定义函数的 helpers.php 文件。

我们看到一小段带有 if 语句的代码,但无论哪种方式,它都返回相同的类,即 AuthFactory

所以我们再次在 Ctrl + clickAuthFactory,我们发现自己盯着 Factory 接口命名空间 Illuminate\Contracts\Auth;

现在我们可以使用 PHPDocs 告诉 Intelephense 一个名为 attempt 的方法可以用于此接口的实例。请注意下面完整代码中 interface Factory 声明上方的“注释”(PHPDocs)。

<?php

namespace Illuminate\Contracts\Auth;

/**
 * @method attempt
 */
interface Factory
{
    /**
     * Get a guard instance by name.
     *
     * @param  string|null  $name
     * @return \Illuminate\Contracts\Auth\Guard|\Illuminate\Contracts\Auth\StatefulGuard
     */
    public function guard($name = null);

    /**
     * Set the default guard the factory should serve.
     *
     * @param  string  $name
     * @return void
     */
    public function shouldUse($name);
}

瞧!

注意

只有在该方法确实存在时才应该这样做,否则你就是在钉自己的棺材。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。