Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

laravel

model

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?

like image 611
David Avatar asked Jul 26 '17 14:07

David


2 Answers

You need to pass an array of Skill objects to the saveMany() method:

$skillModels = [];
foreach ($request->skills as $skill) {
    $skillsModels[] = new Skill($skill);
}

$user->skills()->saveMany($skillModels);

And you're passing a simple array.

like image 110
Alexey Mezenin Avatar answered Nov 15 '22 22:11

Alexey Mezenin


Just try createMany instead :)

$post->comments()->createMany([
    ['message' => 'A new comment.'],
    ['message' => 'Another comment.'],
]);

See the doc: https://laravel.com/docs/7.x/eloquent-relationships#the-create-method

like image 40
Elbo Shindi Pangestu Avatar answered Nov 15 '22 21:11

Elbo Shindi Pangestu