Laravel auth()->user->posts()->create($data); > 未定义属性

huangapple go评论56阅读模式
英文:

Laravel auth()->user->posts()->create($data); > Undefined property

问题

我是后端开发的新手,所以我正在尝试在互联网上做很多教程,以便掌握这个领域。

目前我正在尝试完成一个两年前的Instagram克隆教程,所以我正尝试按照文档来更新和运行我的代码。

我正在尝试创建帖子,我的web.php中的路由是:

Route::post('/post', [App\Http\Controllers\PostsController::class, 'store']);

我的PostController.php中的store函数如下:

public function store()
{
    $data = request()->validate([
       'caption' => 'required',
       'image' => 'required|image' 
    ]);

    auth()->user()->posts()->create($data);

    Post::create($data);

    dd(request()->all());
}

在User.php中,我还定义了:

public function posts()
{
    return $this->hasMany(Post::class);
}

它一直告诉我“未识别的方法'posts'。intelephense(1013)”。

我已经搜索并找到了类似于教程的这一部分的问题,但我无法解决它,我想知道是否只是另一种版本问题。

感激任何帮助。
谢谢!

英文:

I am new to backend development so I am trying to do a lot of tutorials on the internet to get the hang of this.

ATM I am trying to do a 2 year old tutorial for an Instagram Clone so I am trying to follow it while using the documentation for the current version of laravel to update and run my code.

I am trying to create posts, my Route in web.php is

Route::post('/post', [App\Http\Controllers\PostsController::class, 'store']);

My store function in PostController.php

    public function store()
    {
        $data = request()->validate([
           'caption' => 'required',
           'image' => 'required|image' 
        ]);

        auth()->user()->posts()->create($data);

        Post::create($data);

        dd(request()->all());
    }

In the User.php I also defined

    public function posts()
    {
        return $this->hasMany(Post::class);
    }

It keeps telling me "unidentified method 'posts'. intelephense(1013)

I have searched and found similar problems with this part of the tutorial but I couldn't fix it and I was wondering if it's just another case of different version problem .

I'd appreciate any help.
Thank you!

I am trying to make the post command work and while following the tutorial, it gave me this error saying the function is not defined.

答案1

得分: 1

我猜问题出在你的编辑器上,我在 PhpStorm 中测试了一下,一切都很正常。之后我进行了一些研究,找到了这篇帖子,我认为你遇到了相同的问题,检查一下:

链接

英文:

I quess the problem is your editor, I am testing your issue in PhpStorm and anythings works fine for me, after that I do a little research and I found this post, i think you have the same problem, check it:

link

huangapple
  • 本文由 发表于 2023年3月31日 18:08:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/75897290.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定