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?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With