Home > Backend Development > PHP Tutorial > How to use Eloquent?

How to use Eloquent?

Barbara Streisand
Release: 2024-10-14 06:13:29
Original
870 people have browsed it

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
Copy after login

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'];
}
Copy after login

$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!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template