【问题标题】:Laravel auth()->user()->posts()->create($data); > Undefined method 'post'.intelephense(1013)Laravel auth()->user()->posts()->create($data); > 未定义的方法'post'.intelephense(1013)
【发布时间】:2021-09-15 01:12:55
【问题描述】:

我已经学习了 2 个小时的教程,但现在我遇到了问题。本教程使用的是旧版本的 Laravel。我正在创建 Instagram 克隆,并想创建帖子。

web.php

Route::post('/p', 'PostsController@store');

PostsController

public function store()
{
    $data = request()->validate([
        'caption' => 'required',
        'image' => ['required', 'image'],
    ]);
    
    /* I got an error at this line saying undefined method post() */
    auth()->user()->posts()->create($data);
}

用户模型

public function posts()
{
    return $this->hasMany(Post::class)
        ->orderBy('created_at', 'DESC');
}

【问题讨论】:

    标签: php laravel authentication


    【解决方案1】:

    您应该将posts() 方法放在User 模型中,而不是UserController

    【讨论】:

    • 我的错我打算写用户而不是用户控制器。我现在纠正了这个问题,但不幸的是它不起作用
    【解决方案2】:

    这似乎是由 Intellephense 引起的常见问题。 似乎在这里得到了回答: https://stackoverflow.com/a/59266972/14440607

    本质上,IDE 助手会生成代码来帮助您的 IDE 提供准确的建议。 https://github.com/barryvdh/laravel-ide-helper

    【讨论】:

    • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
    • 虽然此链接可能会回答问题,但最好在此处包含答案的基本部分并提供链接以供参考。如果链接页面发生更改,仅链接答案可能会失效。 - From Review
    猜你喜欢
    • 2020-07-16
    • 1970-01-01
    • 1970-01-01
    • 2022-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-08
    • 2019-03-29
    相关资源
    最近更新 更多