Tutorial

How To Create a Database Model in Laravel with Eloquent

PHPPHP FrameworksDevelopmentDatabasesLaravel
Part of the Series: How To Build a Links Landing Page in PHP with Laravel and Docker Compose

Laravel is an open-source PHP framework that provides a set of tools and resources to build modern PHP applications. In this project-based tutorial series, you’ll build a Links Landing Page application with the Laravel framework, using a containerized PHP development environment managed by Docker Compose.

At the end, you’ll have a one-page website built with Laravel and managed via Artisan commands where you can share relevant links to an audience on social channels and presentations.

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
Output
Model 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:

app/Models/Link.php
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

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.

Creative Commons License