Skip to content

Models in Sparkle ​

Introduction ​

Models in Sparkle provide an abstraction layer for interacting with database tables. Each model represents a database table and allows querying, inserting, updating, and deleting records easily.

Defining a Model ​

To create a new model, extend the Model class and define the table name and primary key.

Extending the Model ​

You must extend Sirmerdas\Sparkle\Model\Model to create a model.

php
use Sirmerdas\Sparkle\Model\Model;

class ExampleModel extends Model
{
    protected string $table = 'example_table';
    protected string $primaryKey = 'id';
}

Explanation of Properties ​

PropertyTypeDescription
$tablestringDefines the database table associated with the model.
$primaryKeystringSpecifies the primary key column of the table. Default value is id.

Example: User Model ​

Here’s an example of a User model that interacts with the exams table.

php
use Sirmerdas\Sparkle\Model\Model;

class User extends Model
{
    protected string $table = 'users';
    protected string $primaryKey = 'id';
}

Usage ​

After defining the model, you can use it to interact with the database.

Fetch All Records ​

php
$users = Users::all();

Find a Record by Primary Key ​

php
$user = User::find(2);

TIP

You can use all Query Builder methods within models, both statically and through method chaining, without needing to define the table each time.

Example:

php
User::limit(10)->get();

Summary ​

By extending Model, you can easily work with database tables using a structured approach.

Released under the MIT License.