Table of Contents
1. Creating Models and Migrations
2. Basic CRUD Operations
Retrieve All Records
Find a Record by ID
Create a New Record
Update a Record
Delete a Record
3. Using Eloquent Relationships
Define a Relationship (eg, Post belongs to User)
4. Querying with Eloquent
Scopes (Reusable Queries)
5. Mass Assignment Protection
6. Soft Deletes (Optional)
7. Accessors and Mutators
Mutator (set)
Accessor (get)
Home PHP Framework Laravel How to use Eloquent in Laravel

How to use Eloquent in Laravel

Aug 21, 2025 pm 02:30 PM
laravel eloquent

Create models and migration: Use php artisan make:model Post -m to generate models and migration files, define table structure and run php artisan migrate; 2. Basic CRUD operations: use Post::all(), find(), create(), save() and delete() methods to query, create, update and delete data; 3. Use Eloquent association: define belongsTo and hasMany relationships in the model, and use the with() method to preload the associated data to avoid N 1 query problems; 4. Eloquent query: use query constructor to chain calls such as where, orderBy and other methods, and reuse query logic through local scopePublished; 5. Batch assignment protection: Set $fillable or $guarded in the model Attributes to prevent unexpected assignment; 6. Soft Deletion: Introduce SoftDeletes trait and add softDeletes() to the migration, use delete() and restore() to control soft deletion and recovery; 7. Accessories and modifiers: Automatically process data formats when setting or obtaining attributes through setTitleAttribute and getTitleAttribute. Eloquent interacts with the database through the model, so that developers can efficiently operate data without writing native SQL. It is recommended that each table correspond to a model, reasonably define the association relationship and make full use of the functions provided by Eloquent to complete data operations, and ultimately achieve a clear and maintainable code structure.

How to use Eloquent in Laravel

Eloquent is Laravel's built-in ORM (Object-Relational Mapper) that makes it easy to interact with your database using PHP syntax instead of writing raw SQL. It's powerful, expressive, and beginner-friendly once you understand the basics. Here's how to use Eloquent effectively in Laravel.

How to use Eloquent in Laravel

1. Creating Models and Migrations

Every database table has a corresponding Eloquent model. To create a model along with a migration, run:

 php artisan make:model Post -m

This creates:

How to use Eloquent in Laravel
  • app/Models/Post.php (the model)
  • database/migrations/xxxx_xx_xx_create_posts_table.php (the migration)

In the migration file, define your table structure:

 Schema::create('posts', function (Blueprint $table) {
    $table->id();
    $table->string('title');
    $table->text('content');
    $table->foreignId('user_id')->constrained();
    $table->timestamps();
});

Run the migration:

How to use Eloquent in Laravel
 php artisan migrate

Now you can use the Post model to interact with the posts table.

Note: If your model is in a folder like Models , make sure to reference it correctly or update the default namespace in config/auth.php if needed.


2. Basic CRUD Operations

Once your model is set up, you can perform basic operations.

Retrieve All Records

 $posts = Post::all();

Find a Record by ID

 $post = Post::find(1);
// or throw an exception if not found
$post = Post::findOrFail(1);

Create a New Record

 Post::create([
    'title' => 'My First Post',
    'content' => 'Hello World',
    'user_id' => 1,
]);

Or manually:

 $post = new Post();
$post->title = 'Another Post';
$post->content = 'More content';
$post->user_id = 1;
$post->save();

Update a Record

 $post = Post::find(1);
$post->title = 'Updated Title';
$post->save();

Or use mass update:

 Post::where('id', 1)->update(['title' => 'Updated']);

Delete a Record

 $post = Post::find(1);
$post->delete();

// or delete directly
Post::destroy(1);

3. Using Eloquent Relationships

Eloquent makes defining relationships between models simple.

Define a Relationship (eg, Post belongs to User)

In the Post model:

 public function user()
{
    return $this->belongsTo(User::class);
}

In the User model:

 public function posts()
{
    return $this->hasMany(Post::class);
}

Now you can access related data:

 $post = Post::with('user')->find(1);
echo $post->user->name; // Access the author

$user = User::find(1);
foreach ($user->posts as $post) {
    echo $post->title;
}

Use with() to eager load relationships and avoid N 1 query problems.


4. Querying with Eloquent

Eloquent models extend the query builder, so you can chain methods:

 $publishedPosts = Post::where('status', 'published')
    ->where('created_at', '>', now()->subDays(7))
    ->orderBy('created_at', 'desc')
    ->get();

Scopes (Reusable Queries)

Define a local scope in your model:

 public function scopePublished($query)
{
    return $query->where('status', 'published');
}

Use it:

 $posts = Post::published()->get();

5. Mass Assignment Protection

To use create() or update() safely, define fillable or guarded fields.

In your model:

 protected $fillable = ['title', 'content', 'user_id'];

Or, alternatively:

 protected $guarded = []; // allows all, but less secure

6. Soft Deletes (Optional)

To "delete" records without removing them from the database:

  • Add use Illuminate\Database\Eloquent\SoftDeletes; to your model.
  • Add $table->softDeletes(); in your migration.
  • Then use ->delete() — it sets deleted_at instead of removing the row.

Restore a soft-deleted record:

 $post = Post::withTrashed()->find(1);
$post->restore();

7. Accessors and Mutators

Modify data when getting or setting attributes.

Mutator (set)

 public function setTitleAttribute($value)
{
    $this->attributes['title'] = ucfirst($value);
}

Accessor (get)

 public function getTitleAttribute($value)
{
    return ucfirst($value);
}

Now every time you get or set title , it's capitalized.


Eloquent makes working with databases in Laravel intuitive and clean. Start with models and basic queries, then gradually use relationships, scopes, and accessors as your app grows. Most of the time, you won't need raw SQL.

Basically, just remember: one model per table, definition relationships, and let Eloquent do the heavy lifting.

The above is the detailed content of How to use Eloquent in Laravel. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

ArtGPT

ArtGPT

AI image generator for creative art from text prompts.

Stock Market GPT

Stock Market GPT

AI powered investment research for smarter decisions

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

How to use Eloquent in Laravel How to use Eloquent in Laravel Aug 21, 2025 pm 02:30 PM

Create models and migration: Use phpartisanmake:modelPost-m to generate models and migration files, define the table structure and run phpartisanmigrate; 2. Basic CRUD operations: use Post::all(), find(), create(), save() and delete() methods to query, create, update and delete data; 3. Use Eloquent association: define belongsTo and hasMany relationships in the model, and use the with() method to preload the associated data to avoid N 1 query problems; 4. Eloquent query: use query constructor to chain calls such as where

How to work with Polymorphic Relationships in Laravel How to work with Polymorphic Relationships in Laravel Aug 25, 2025 am 10:56 AM

PolymorphicrelationshipsinLaravelallowamodellikeCommentorImagetobelongtomultiplemodelssuchasPost,Video,orUserusingasingleassociation.2.Thedatabaseschemarequires{relation}_idand{relation}_typecolumns,exemplifiedbycommentable_idandcommentable_typeinaco

How to create a social network with Laravel How to create a social network with Laravel Sep 01, 2025 am 06:39 AM

Yes,youcancreateasocialnetworkwithLaravelbyfollowingthesesteps:1.SetupLaravelusingComposer,configurethe.envfile,enableauthenticationviaBreeze/Jetstream/Fortify,andrunmigrationsforusermanagement.2.Implementcorefeaturesincludinguserprofileswithavatarsa

How to use Laravel's Task Scheduling How to use Laravel's Task Scheduling Aug 31, 2025 am 06:07 AM

Laravel's TaskScheduling system allows you to define and manage timing tasks through PHP, without manually editing the server crontab, you only need to add a cron task that is executed once a minute to the server: *cd/path-to-your-project&&phpartisanschedule:run>>/dev/null2>&1, and then all tasks are configured in the schedule method of the App\Console\Kernel class; 1. Defining tasks can use command, call or exec methods, such as $schedule-

How to build a mobile app backend with Laravel How to build a mobile app backend with Laravel Sep 02, 2025 am 08:34 AM

Using Laravel to build a mobile backend requires first installing the framework and configuring the database environment; 2. Define API routes in routes/api.php and return a JSON response using the resource controller; 3. Implement API authentication through LaravelSanctum to generate tokens for mobile storage and authentication; 4. Verify file type when uploading files and store it on public disk, and create soft links for external access; 5. The production environment requires HTTPS, set current limits, configure CORS, perform API version control and optimize error handling. It is also recommended to use API resources, paging, queues and API document tools to improve maintainability and performance. Use Laravel to build a safe,

How to internationalize a Laravel application How to internationalize a Laravel application Aug 22, 2025 pm 02:31 PM

Create language files: Create subdirectories for each language (such as en, es) in the resources/lang directory and add messages.php file, or use JSON file to store translation; 2. Set application language: read the request header Accept-Language through middleware or detect language through URL prefix, set the current language using app()->setLocale(), and register the middleware in Kernel.php; 3. Use translation functions: use __(), trans() or @lang in the view, and use __() that supports fallback; 4. Support parameters and plural: Use placeholders in translation strings such as: n

How to log messages to a file in Laravel? How to log messages to a file in Laravel? Sep 21, 2025 am 06:04 AM

LaravelusesMonologtologmessagesviatheLogfacade,withdefaultlogsstoredinstorage/logs/laravel.log.Configurechannelsinconfig/logging.phptocontroloutput;thedefaultstackchannelaggregatesmultiplehandlerslikesingle,whichwritestoafile.UseLog::info(),Log::warn

How to implement a 'remember me' functionality in Laravel How to implement a 'remember me' functionality in Laravel Aug 31, 2025 am 08:53 AM

Ensure that there is a remember_token column in the user table. Laravel's default migration already includes this field. If not, it will be added through migration; 2. Add a check box with name remember in the login form to provide the "Remember Me" option; 3. Pass the remember parameter to the Auth::attempt() method during manual authentication to enable persistent login; 4. "Remember Me" lasts for 5 years by default, and can be customized through the remember_for configuration item in config/auth.php; 5. Laravel automatically invalidates remember_token when password changes or user deletes. It is recommended to use HTTPS to ensure security in the production environment; 6

See all articles