phplaravelintelephense

Undefined method 'usersCoolPosts', but both the project and method is working/running fine


The intelephense tells me that I have an undefined method which is 'userCoolPosts' from routes/web.php, but as you can see below, the method exists in the User.php from app/Models folder. Upon testing my project, the method is working fine but the error in the console persists.

web.php

Route::get('/', function () {
    $posts = [];
    if (Auth::check()) {
        $posts = Auth::user()->usersCoolPosts()->latest()->get();
    }
    return view('home', ['posts' => $posts]);
});

User.php from app/Models folder

    protected function casts(): array
    {
        return [
            'email_verified_at' => 'datetime',
            'password' => 'hashed',
        ];
    }

    public function usersCoolPosts()
    {
        return $this->hasMany(Post::class, 'user_id');
    }
}

I did reindex Intelephense (index workspace), and still the error persists.


Solution

  • Auth::user() returns \Illuminate\Contracts\Auth\Authenticatable|null. Which does not have your method.

    You can safely ignore this message. Personally I use https://github.com/barryvdh/laravel-ide-helper Which resolves such issues by rewriting the expected output to your User model.