Laravel «Метод Illuminate \\ Database \\ Eloquent \\ Collection :: create не существует». ошибка при создании сообщения для текущего пользователя - PullRequest
0 голосов
/ 15 января 2020

Я хочу вставить запись в таблицу posts для текущего пользователя, вошедшего в систему через отношения Eloquent, но он возвращает ошибку. Мой код

return new PostResource(auth()->user()->posts->create([
   'title' => 'lorem',
   'body' => 'ipsum',
]));

Ошибка

 "message": "Method Illuminate\\Database\\Eloquent\\Collection::create does not exist.",
    "exception": "BadMethodCallException",
    "file": "C:\\xampp\\htdocs\\laravel\\vendor\\laravel\\framework\\src\\Illuminate\\Support\\Traits\\Macroable.php",
    "line": 103,

Пользователь. php

protected $guarded = [];

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

Пост. php

protected $guarded = [];

public function user()
{
   return $this->belongsTo('App\User');
}

PostResource. php

public function toArray($request)
{
   return [
     'title' => $this->title,
     'body' => $this->body,
     'created_at' => Carbon::parse($this->created_at)->format('Y-m-d H:m' ),
     'updated_at' => Carbon::parse($this->updated_at)->format('Y-m-d H:m' )
   ]
}

миграция пользовательских таблиц

public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->enum('role',['user','admin'])->default('user');
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
    }

Миграция таблицы сообщений

public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title');
            $table->longText('body');
            $table->unsignedInteger('user_id');
            $table->timestamps();

            $table->foreign('user_id')->references('id')->on('users');
        });
    }

1 Ответ

0 голосов
/ 15 января 2020

Вы можете использовать

$post = Post;
$post->title = 'lorem';
$post->body = 'ipsum';
//...
return new PostResource(auth()->user()->posts->save($post));
//...
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...