Skip to content

Início / Optitravel / Models

update($id, array $data, bool $refresh = true)

This method updates an existing record in the database, identified by its primary key. It builds and executes an UPDATE SQL statement using the provided data. Only the fields listed in allowedColumns will be included in the query.

If the update is successful and $refresh is set to true, the model instance is automatically updated with the latest values from the database.

Parameters

  • $id – The value of the primary key identifying the record to update.

  • array $data – An associative array where keys represent column names and values are the new values to assign.

Returns:

true if the update succeeds, or false if it fails or if no valid data was provided.

Example

use \App\Models\User;

$user = new User();
$success = $user->update(1, [
    'email' => 'example@optigest.net',
    'status' => 'I'
]);

if ($success) {
    echo "User updated: " . $user->email;
} else {
    echo "Update failed.";
}

Notes

  • Fields not listed in allowedColumns are automatically excluded from the update.

  • The method uses prepared statements to prevent SQL injection.

  • If refresh is true, a find($id) is executed and the model's current object is updated in-place.

Behavior

  • If no valid columns are present in the $data, the method returns false.

  • When $refresh is true, the object reflects the updated state immediately after the call.


(Última atualização: 13/05/2025)