首页 > 解决方案 > 找不到方法商店和帖子 [LARAVEL]

问题描述

我在后端问题上被困了一段时间。PHPStorm 告诉我posts 和store 方法不存在,不知道用什么方法来解决这个问题...

文件 PostController.php:

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

     $imagePath = request('image')->store('uploads','public');

     auth()->user()->posts()->create([
         'caption' => $data['caption'],
         'image' => $imagePath
         ]);

     return redirect()->route('profiles.show', ['user' => auth()->user()]);
    }

文件用户.php:

class User extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'username', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    public function getRouteKeyName()
    {
        return 'username';
    }

    public function profile(){
        return $this->hasOne('App\Profile');
    }
}

遇到的错误:

错误顶部

完全错误

标签: phplaravel

解决方案


我没有在我的 User.php 中创建关系帖子。

所以我以这种方式添加了关系:

public function posts(){
        return $this->hasMany('App\Post');
    }

推荐阅读