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?
- 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
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
- 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'];
}
$table: Specifies the table name.
$fillable: Defines the attributes that can be mass-assigned.
Top comments (0)