Jake
Jake

Reputation: 3

Laravel save() shows undefined method

I'm new to Laravel and currently I am facing an issue.

I'm trying to insert a record to another database, but when I try to save it, it throws the below Error:

Call to undefined method Illuminate\Database\Query\Builder::save()

Here is my code:

$targetedCustomer = Customer::on($this->connection)->where('fusercode', $user->loginname)->first();
if($targetedCustomer->agent_code != $user->agent)
{
    $targetedCustomer->agent_code = $user->agent;
    $targetedCustomer->save();

    $logs = CustomerAgentCodeUpdateLog::on($this->connection);
    $logs->customer_id =  $targetedCustomer->customer_id;
    $logs->old_agent_code = $targetedCustomer->agent_code;
    $logs->new_agent_code = $user->agent;
    $logs->type = 1;
    $logs->save();
}

Upvotes: 0

Views: 1249

Answers (2)

Mustafa Ehsan Alokozay
Mustafa Ehsan Alokozay

Reputation: 5823

The Illuminate\Database\Eloquent\Model::on() method returns an instance of Illuminate\Database\Eloquent\Builder class which doesn't have any method named save(). Therefore you have to do something like below to make it work:

$logs = CustomerAgentCodeUpdateLog::on($this->connection);

$logs->create([
    'customer_id' =>  $targetedCustomer->customer_id;
    'old_agent_code' => $targetedCustomer->agent_code;
    'new_agent_code' => $user->agent;
    'type' => 1;
]);

You don't need to call save().

Upvotes: 2

W Kristianto
W Kristianto

Reputation: 9303

Try this method :

$targetedCustomer = Customer::on($this->connection)
    ->where('fusercode', $user->loginname)
    ->first();

if($targetedCustomer and $targetedCustomer->agent_code != $user->agent)
{
    // Set agent code
    $targetedCustomer->agent_code = $user->agent;
    $targetedCustomer->save();

    // New log
    $logs                 = (new CustomerAgentCodeUpdateLog)->on($this->connection); // with `new`
    $logs->customer_id    = $targetedCustomer->customer_id;
    $logs->old_agent_code = $targetedCustomer->agent_code;
    $logs->new_agent_code = $user->agent;
    $logs->type           = 1;
    $logs->save();
}

Upvotes: 0

Related Questions