'In Laravel Eloquent, how do you UPDATE a model with a cast encrypted field in a table with a composite primary key?

I finally found out how to update data in a table with a composite primary key in Laravel. This is how. (Let's say the Vehicles table has a composite primary key of "make" and "model")

Vehicle::where("make", $make)->where("model", $model)->update([
  "notes" => $notes,
]);

However, in my models/Vehicle.php file, I'm casting the "notes" columns to be encrypted, like this:

public $casts = [
  'notes' => 'encrypted',
];

Putting the above two things together does not work. The "notes" column will be saved with clear text, not encrypted.

However, if I create the record using Vehicle::create(["make"=>$make, "model"=>$model, "notes"=>$notes]), the "notes" column WILL be encrypted as expected when the record is created. But once it's created, how can I update it?

p.s. In order to even get creating to work, I had to add this line to the model file:

public $incrementing = false;


Solution 1:[1]

One way to do it is like this, but I would still like a solution that went through an actual Model.

Vehicle::where("make", $make)->where("model", $model)->update([
  "notes" => Crypt::encrypt($notes, false),
]);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1