Reputation: 1672
I have the following models:
Below are the relationships:
User belongsTo a group
Group hasMany Users
Device belongsTo group
How can i create a Device
through user?
$user = Auth::user();
$new_device = new Device;
$new_device->ip = $request->input('ip');
$new_device->port = $request->input('port');
$new_device->community_name = $request->input('community_name');
$user->group->save($new_device);
Error I am getting when using:
$user->group->save($new_device);
Argument 1 passed to Illuminate\Database\Eloquent\Model::save() must be of the type array, object given, called in /home/snmpexperiments/laravel/app/Http/Controllers/SnmpController.php on line 74
Error I am getting when using:
$user->group()->save($new_device);
Call to undefined method Illuminate\Database\Eloquent\Relations\BelongsTo::save()
I am kind of confused..should i save the device through the group or should i save the device through user?
User Model
public function group()
{
return $this->belongsTo('App\Group');
}
public function devices()
{
return $this->hasManyThrough('App\Device', 'App\Group'); // So i can get devices like $user->devices
}
Group Model
public function users()
{
return $this->hasMany('App\User');
}
public function devices()
{
return $this->hasMany('App\Device');
}
public function interfaces(){
return $this->hasManyThrough('App\ModelInterface', 'App\Device'); // So I can get interfaces through Device $group->interfaces
}
Device Model
public function interfaces()
{
return $this->hasMany('App\ModelInterface');
}
public function group()
{
return $this->belongsTo('App\Group');
}
Upvotes: 0
Views: 44
Reputation: 548
To save the device through group you would need to specify device.
$user->group->device()->save($new_device);
The way you are doing it your trying to save the group model. The model->save() can accept an array of options that's why you are getting that error.
Upvotes: 0
Reputation: 23011
The correct syntax is $post->comments()->save($comment);
. Note the parenthesis after comments, which accesses the relationship method instead of the property. So in this case you would use
$user->group->devices()->save($new_device);
Upvotes: 2