How To Create a Database Model in Laravel with Eloquent

Eloquent is an object relational mapper (ORM) included by default within the Laravel framework. It facilitates the task of interacting with database tables, providing an object-oriented approach to inserting, updating, and deleting database records, while also providing a streamlined interface for executing SQL queries.

Eloquent uses database models to represent tables and relationships in supported databases. The name of the database table is typically inferred from the model name, in plural form. For instance, a model named Link will use links as its default table name.

You can use the artisan make:model command line helper to generate new models for your application. To create a new Eloquent model for your links table, run:

  • docker-compose exec app php artisan make:model Link
OutputModel created successfully. 

This will generate a new file containing a barebones model class. Even though this class has no apparent properties or methods, when operating the model via facades, you have access to the underlying Eloquent database classes that are able to identify database table structures and represent them as fully-functional objects.

For your reference, this is the automatically generated model class:


<?php  namespace AppModels;  use IlluminateDatabaseEloquentFactoriesHasFactory; use IlluminateDatabaseEloquentModel;  class Link extends Model {     use HasFactory; }  

For the purpose of this series, you don’t need to make any changes to this file. If you want to extend the application in the future, you might use this model to create custom methods for the Link class that involve database operations. Additionally, if you want to create relationships between the Link model and other models, you’ll need to include a method representing the relationship in at least one of the sides. For detailed information about Eloquent relationships, please refer to the official documentation.

In the next part of this series, you’ll create Artisan commands that will use this model to select, insert, and delete links on your database.