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?
a. Creating a Model
You can create a model using the artisan command:
php artisan make:model Post
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
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']; }
$table: Specifies the table name.
$fillable: Defines the attributes that can be mass-assigned.
See Full Tutorials
The above is the detailed content of How to use Eloquent?. For more information, please follow other related articles on the PHP Chinese website!