Can we see your membership() relationship on the model?
May 12, 2015
11
Level 15
save() on polymorphic relation don't work
Hi,
I want to save records for polymorphic tables.
<?php namespace App\Commands;
use App\Commands\Command;
use App\Http\Requests\CustomerRequest;
use App\Http\Requests\UserRequest;
use App\User;
use App\Customer;
use Illuminate\Contracts\Bus\SelfHandling;
use Illuminate\Foundation\Bus\DispatchesCommands;
use Illuminate\Queue\SerializesModels;
class CreateCustomerMemberCommand extends Command implements SelfHandling {
use SerializesModels, DispatchesCommands;
/**
* @var \App\Http\Requests\UserRequest
*/
private $userRequest;
/**
* Create a new command instance.
*
* @param \App\Http\Requests\UserRequest $userRequest
* @param \App\Http\Requests\CustomerRequest $customerRequest
*/
public function __construct(UserRequest $userRequest)
{
$this->user = new User;
$this->customer = new Customer;
$this->userRequest = $userRequest;
}
/**
* Execute the command.
*
* @param \App\Http\Requests\CustomerRequest $customerRequest
*
* @return
* @internal param \App\User $user
*/
public function handle(CustomerRequest $customerRequest)
{
// TODO: Change UserRequest to an CustomerRequest
$customer = $this->dispatch(new CreateCustomerCommand($customerRequest));
$user = $this->dispatch(new CreateUserCommand($this->userRequest));
return $user->membership()->save($customer);
}
}
<?php namespace App\Commands;
use App\Commands\Command;
use App\Customer;
use App\Http\Requests\CustomerRequest;
use App\Http\Requests\UserRequest;
use Illuminate\Contracts\Bus\SelfHandling;
class CreateCustomerCommand extends Command implements SelfHandling {
/**
* @var \App\Http\Requests\UserRequest
*/
private $request;
/**
* Create a new command instance.
*
* @param \App\Customer $customer
* @param \App\Http\Requests\UserRequest $request
*/
public function __construct(CustomerRequest $request)
{
$this->request = $request;
}
/**
* Execute the command.
*
* @return void
*/
public function handle()
{
$customer = new Customer;
$customer->firstname = $this->request->get('firstname');
$customer->lastname = $this->request->get('lastname');
$customer->save();
return $customer;
}
}
When I dd the $user on CreateCustomerMemberCommand::handle() I get it right. But if I want to save it, I get the following error:
BadMethodCallException in Builder.php line 1992:
Call to undefined method Illuminate\Database\Query\Builder::save()
Don't know what to do.
Thanks
Level 53
@MichaelGrossklos There's no save on belongsTo and morphTo - these are child relations, so you need to have the parent saved, before you can create such relationship with associate. Like this:
$customer->save();
$user->membership()->associate($customer);
1 like
Please or to participate in this conversation.