Início / Optitravel / Models
insert(array $data = [])
This method inserts a new record into the table represented by the model. It builds and executes an INSERT SQL statement using the provided data or, if no data is passed, it uses the current state of the object ($this->toArray()).
If the model defines a beforeInsert() method, it will be called before executing the SQL, allowing you to modify or validate the data.
After insertion, if the model has a primary key and no data was explicitly passed (i.e., insertion was based on the current object), the object will be automatically updated with the newly inserted data.
Parameters
array data (optional) – An associative array containing the data to insert. The keys must match the allowed column names. If empty, the current object state ($this->toArray()) will be used.
Returns
The value of the primary key of the newly inserted row (if defined), true if no primary key exists, or null if the operation fails.
Example
use \App\Models\User;
$user = new User();
$user->name = 'Optigest';
$user->username = 'opti';
$user->password = '*********';
$user->email = 'example@optigest.net';
$user->status = 'A';
$user->lang = 'pt';
$user->system_id = 'SYSTEM';
$user->access_level = '99';
$user->create_time = date('Y-m-d H:i:s');
$user->last_change_time = date('Y-m-d H:i:s');
// Insert using the object itself
$id = $user->insert();
echo "New user ID: $id";
Notes
-
Only columns listed in allowedColumns are considered during insertion. Invalid columns may be ignored or cause an exception depending on implementation.
-
Use the optional beforeInsert(array &$data) method in your model to manipulate or validate data before it is saved.
-
The method uses prepared statements internally to avoid SQL injection.
Behavior
-
If $data is provided, that data is inserted and the object remains unchanged.
-
If $data is not provided:
-
The object’s current data is inserted.
-
The object is updated with the inserted row's data (e.g., the auto-generated primary key).
-
A find() is called to reload the full record into the object.
↑ (Última atualização: 13/05/2025)