Reputation: 99
I have a simple form, one of the fields is 'resource'. I have an Item model which has many Resources. I'm trying to save both the Item and it's Resource from my form.
Item.php:
public function resource()
{
return $this->hasMany('App\Resource');
}
public function addResource(Resource $resource)
{
return $this->resource->save($resource);
}
Resource.php:
public function item()
{
return $this->belongsTo('App\Item');
}
My save method in ItemsController:
public function store(CreateItemRequest $request)
{
//get and save Item
$item = new Item($request->all());
Auth::user()->item()->save($item);
//get and save Resource
$resource = new Resource(array($request->input('resource')));
$item->addResource($resource);
return view('items.index');
}
When calling addResource on the Item model, I get this error:
BadMethodCallException in Macroable.php line 81:
Method save does not exist.
in Macroable.php line 81
at Collection->__call('save', array(object(Resource))) in Item.php line 41
at Item->addResource(object(Resource)) in ItemsController.php line 73
at ItemsController->store(object(CreateItemRequest))
at call_user_func_array(array(object(ItemsController), 'store'), array(object(CreateItemRequest))) in Controller.php line 76
I've been stuck on this for way too long! Any help would be MUCH appreciated. I'm sure it's a simple newbie mistake...
Upvotes: 2
Views: 4740
Reputation: 24671
Your addResource()
method should look like this:
public function addResource(Resource $resource)
{
$this->resource()->attach($resource->id);
}
The property $this->resource
will be resolved to an actual instance of a related model. If no models have yet been related it will evaluate to null
. The method $this->resource()
will actually return the type of relationship that exists between the models (in this case, it should return Illuminate\Database\Eloquent\Relations\HasMany
).
Upvotes: 1