Laravel Argument 1 passed to HasOneOrMany::save() must be an instance of Model array given

Viewed 18480

I'm new at Laravel and I have a problem when I try to save array of data to database. Here's the error I get

Argument 1 passed to Illuminate\Database\Eloquent\Relations\HasOneOrMany::save() must be an instance of Illuminate\Database\Eloquent\Model, array given, called in S:\Documents\samdyk\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Relations\HasOneOrMany.php on line 267 and defined

So here's my code

class Skill extends Model
{
    protected $fillable = ['skill_title', 'knowledge_level'];
}

class User extends Authenticatable
{
    use Notifiable;

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

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

    public function skills() {
        return $this->hasMany(Skill::class);
    }
}

And here's the controller function

public function editMyProfile(Request $request) {
        $user = Auth::user();

        dump($request->get('skills'));
       // dump($request->get('skills')[0]);
        dump($user->skills()->saveMany($request->get('skills')));
       return 1;
}

So here's $request->get('skills') data

array:5 [
  0 => array:2 [
    "skill_title" => "fghjghj"
    "knowledge_level" => "20"
  ]
  1 => array:2 [
    "skill_title" => "gjghjhgj"
    "knowledge_level" => "50"
  ]
  2 => array:2 [
    "skill_title" => "ghjhgjgfjh"
    "knowledge_level" => "80"
  ]
  3 => array:2 [
    "skill_title" => "hjkhgkkkhgjkjhkhjgk"
    "knowledge_level" => "53"
  ]
  4 => array:2 [
    "skill_title" => "jghjhgjhgj"
    "knowledge_level" => "57"
  ]
]

So as you can see I try to save an array (that's obvious). However even on laravel documentation I see this $post = App\Post::find(1);

$post->comments()->saveMany([
    new App\Comment(['message' => 'A new comment.']),
    new App\Comment(['message' => 'Another comment.']),
]);

So why my code is wrong?

2 Answers
Related