Skip to main content

Command Palette

Search for a command to run...

Laravel Models: Unleashing the Power of Properties

Updated
5 min read
Laravel Models: Unleashing the Power of Properties
A

Behold, the coding maestro! 🎩 Armed with PHP, Laravel, Linux, HTML, JavaScript, Jquery & Vue, I conquer both frontend and backend realms. 🚀 Pressure? No match for me. I deliver excellence and exceed expectations with flair. 🌟 Stay ahead, stay cool, and let's conquer the coding universe together! 💻

Introduction

  • The model in Laravel represents a logical abstraction of a database table. It acts as an intermediary between the application and the database, Laravel follows the convention of one model per table, making it easy to organize and manage your application's data.

    As of now, we know that for every table, we have to create a mode and models are very powerful and have lots of properties and methods to make development easier, we will explore the model's property and their use cases in this blog.

Defining a Model

  • To create a model in Laravel, you can use the artisan command-line tool or manually generate a new PHP class.

    Command to create a model php artisan make:model ModelName (Use PascalCase for the model name)

    I prefer to create a model using the artisan command as after that I don’t have to take care of the parent model class and there are other options also available to create files that will require to complete the feature like Controller, Migration, Seeder, Factory, Request, etc.

Model Properties

Let's explore some essential properties of Laravel models

  1. Table Name

    By default, Laravel assumes that the table name corresponds to the snake case plural form of your model name.

    Example

    1. If you have a model named User Laravel Laravel will assume that the corresponding table name is users and for ProductCategory the table name will be product_categories.

    2. You can also override this and assign the custom table name of your choice to the model’s $table property.

      protected $table = 'your_table_name';

  2. Primary Key

    Laravel assumes the primary key of a table to be an auto-incrementing integer column named id. You can customize this behavior by setting the protected $primaryKey property in your model.

  3. Timestamps

    Laravel provides built-in support for maintaining CREATED_AT and UPDATED_AT timestamps on your model's records.

    By default, these columns are assumed to exist in your table. However, you can disable timestamps by setting public $timestamps = false them in your model.

    You can also override these column names by defining constants on your model,

    you need to define constants CREATED_AT or UPDATED_AT

  4. Soft delete

    Soft deletion in Laravel is a feature that allows you to mark records as "deleted" without actually removing them from the database.

    By default, Laravel uses the ‘deleted_at` column (column is of type DateTime), you can override the column name by just defining a constant with the name ‘DELETED_AT` and assigning the custom column name.

  5. Fillable and Gaurded

    To protect against mass assignment vulnerabilities, Laravel offers two approaches: fillable and guarded attributes.

    Fillable attributes define the fields that can be mass-assigned using the create() or update() methods, while guarded attributes protect fields that should not be mass-assigned.

  6. Relationship Declarations

    Laravel simplifies working with relational databases by providing eloquent relationships.

    You can define relationships between models using methods like hasOne(), hasMany(), belongsTo(), belongsToMany(), and more.

    These relationships enhance data retrieval and simplify querying related data.

  7. Model Events

    Laravel models allow you to define event callbacks for various actions, such as creating, updating, deleting, and retrieving records. These events provide hooks into the model's lifecycle and enable you to execute custom logic when specific actions occur.

  8. Connection

    By default, Laravel assumes that a model will use the default database connection specified in the config/database.php configuration file.

    However, there are cases where you may need to connect to a different database or use a specific connection for a particular model. In such scenarios, you can set the $connection property within your model class to specify the desired database connection.

    protected $connection = 'your_connection_name';

  9. Recently Created

    The public $wasRecentlyCreated property in Laravel is a flag that indicates whether a model instance was recently created and saved to the database.

  10. Model exists

    The public $exists property in Laravel is a flag that indicates whether a model instance exists in the database.

    You may have a model instance that does not correspond to an actual record in the database. In such cases, you can manually set the $exists property to false to indicate that the model instance does not exist in the database.

  11. Global Scope

    The protected static $globalScopes property in Laravel allows you to define global scopes for your Eloquent models.

    Global scopes are conditions that are automatically applied to all queries for a given model. They enable you to define common query constraints that should be applied to every database interaction for that model.

    The $globalScopes property is an array where you can define instances of your global scope classes. Each entry in the array represents a global scope that you want to apply to the model.

  12. Pagination

    The protected $perPage property in Laravel allows you to specify the default number of items to be included in a paginated result set.

    When you retrieve a collection of models and paginate the results using Laravel's pagination feature, the $perPage property determines the number of items that will be displayed per page. By default the value per page value sets to 15, you can modify that on your model by protected $perPage = 30;

Conclusion

  • Laravel models are the backbone of database interaction in your web applications. By leveraging the Eloquent ORM, developers can streamline database operations, define relationships between entities, and implement complex querying with ease. Understanding the various properties and features of Laravel models empowers developers to build robust and maintainable applications efficiently.

More from this blog

A

Abhishek Jha

15 posts

As a Full Stack Developer with four years of extensive expertise in the field of PHP, Laravel, MySQL, Linux, HTML, JavaScript, Jquery & Vue