DEV Community

Cover image for How to use Eloquent?
Saddam Hossain
Saddam Hossain

Posted on

How to use Eloquent?

Eloquent is Laravel’s built-in Object-Relational Mapper (ORM) that provides a simple and efficient way to interact with your database. How to use Eloquent, It allows you to work with database tables as if they were PHP objects and is known for its clean and expressive syntax. Here’s a guide to help you get started with Eloquent.

Steps for How to use Eloquent?

  1. Setting Up Models Each Eloquent model corresponds to a database table, and each instance of the model represents a row in that table.

a. Creating a Model
You can create a model using the artisan command:

php artisan make:model Post
Enter fullscreen mode Exit fullscreen mode

This will create a Post model in the app/Models directory (or app/ for older Laravel versions).

b. Model-Table Conventions
Eloquent assumes some conventions:

Table names are plural (e.g., posts for the Post model).
Primary keys are named id by default.
You can override these conventions if necessary. You Can Learn Laravel 11: How to Generate PDF and Send Emails – Step-by-Step Tutorial

  1. Defining a Model Here’s an example of a simple Post model that interacts with the posts table:
namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    // If your table name differs from the convention
    protected $table = 'posts';

    // Define which fields can be mass-assigned
    protected $fillable = ['title', 'body'];
}
Enter fullscreen mode Exit fullscreen mode

$table: Specifies the table name.
$fillable: Defines the attributes that can be mass-assigned.

See Full Tutorials

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay