Search code examples
phplaravelneovimlanguage-server-protocol

Laravel: Undefined method "cannot"


What's weird about this is that the feature itself works perfectly fine, so I'm guessing it might be an issue with my intelephense but I have no idea how to fix or at least ignore the error message(in a safe way)? Also I am just simply following a tutorial, it's working fine for him and me but I'm just getting that error message.

This is what my function looks like:

public function delete(Post $post) {
    if (auth()->user()->cannot('delete', $post)) {
        return 'You cannot do that';
    }
    $post->delete()
}

I've already searched for this an saw someone suggesting to install a composer package called "laravel-ide-helper" but this didn't do anything.

Also, I'm using neovim with the intelephense LSP (free version) but when switch to another LSP called phpactor, I get a slightly different error message: Method "cannot" does not exist on class "Illuminate\Contracts\Auth\Authenticatable"

Any help much appreciated, thanks.


Solution

  • Using the Request class instead of the global auth() method to get the user seems to get rid of the error and still works as expected (I think the tutorial I was following has slightly outdated content)

    Like this:

    use Illuminate\Http\Request;
    
    public function delete(Request $request, Post $post) {
        if ($request->user()->cannot('delete', $post)) {
             return 'You cannot do that';
        }
        $post->delete()
    }
    

    Refer to the docs: https://laravel.com/docs/10.x/authorization#via-the-user-model