🔧 AI Nachrichten Major AI platforms go down in unprecedented simultaneous outage(03.09.2026 um 17:34 Uhr)
🔧 AI Nachrichten ChatGPT, Claude, and Grok Down? Users Report Widespread Outages(03.09.2026 um 19:14 Uhr)
🔧 AI Nachrichten OpenAI Launches GPT-6 Astra, Says We May Have Entered the AGI Era(03.09.2026 um 22:08 Uhr)
🔧 AI Nachrichten Claude Comes to CarPlay as Fifth Major AI Chatbot App(05.09.2026 um 05:31 Uhr)
🔧 AI Nachrichten OpenAI’s GPT-6 Astra Is AGI, Says NVIDIA CEO Jensen Huang(07.09.2026 um 06:31 Uhr)
🔧 AI Nachrichten Blame AI companies for Mac mini and Mac Studio shortage(31.08.2026 um 10:32 Uhr)
🔧 AI Nachrichten Major AI platforms go down in unprecedented simultaneous outage(03.09.2026 um 17:34 Uhr)
🔧 AI Nachrichten ChatGPT, Claude, and Grok Down? Users Report Widespread Outages(03.09.2026 um 19:14 Uhr)
🔧 AI Nachrichten OpenAI Launches GPT-6 Astra, Says We May Have Entered the AGI Era(03.09.2026 um 22:08 Uhr)
🔧 AI Nachrichten Claude Comes to CarPlay as Fifth Major AI Chatbot App(05.09.2026 um 05:31 Uhr)
🔧 AI Nachrichten OpenAI’s GPT-6 Astra Is AGI, Says NVIDIA CEO Jensen Huang(07.09.2026 um 06:31 Uhr)
🔧 AI Nachrichten Blame AI companies for Mac mini and Mac Studio shortage(31.08.2026 um 10:32 Uhr)

🔧 Programmierung 🕛 kürzlich 5 Min Lesezeit
0

How to Use Eloquent ORM for Database Management in Laravel

↗ Quelle (dev.to)
🗣️ Stimme:
📑 Inhaltsübersicht

Laravel’s Eloquent ORM (Object-Relational Mapping) is one of the most popular features of the framework. It provides a clean, intuitive way to interact with your database, allowing you to work with tables as simple PHP objects. With Eloquent, you can handle complex database operations without writing long and repetitive SQL queries.

This article will walk you through the essentials of using Eloquent ORM for database management, covering everything from creating models to handling relationships and best practices. By the end, you’ll be equipped to use Eloquent effectively in your Laravel projects.





1. Setting Up Eloquent



Before diving into Eloquent, make sure you have a Laravel project set up. If you don’t already have one, you can create it by running the following command:




CODE
composer create-project laravel/laravel example-app






Configuring Your Database

Next, configure your database connection in the .env file located in the root directory of your Laravel project:




CODE
DB_CONNECTION=mysql  
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=your_database_name
DB_USERNAME=your_username
DB_PASSWORD=your_password






Run the following command to create the default database tables, such as the users table:




CODE
php artisan migrate  






Your project is now ready to use Eloquent ORM.






2. Creating a Model



What is a Model?

A model in Eloquent represents a single database table. Each model corresponds to a table, and each instance of the model represents a row in that table. Models handle most of the data manipulation tasks in Laravel.

Creating a Model

To create a new model, use the Artisan command:




CODE
php artisan make:model Post -m  






The -m flag creates a migration file for your model. This migration file defines the structure of the corresponding database table. Open the migration file in the database/migrations directory and define the columns:




CODE
Schema::create('posts', function (Blueprint $table) {  
$table->id();
$table->string('title');
$table->text('body');
$table->timestamps();
});






Run the migration to create the posts table:




CODE
php artisan migrate  









3. Retrieving Data with Eloquent



Retrieving data is one of the most common tasks in database management. With Eloquent, this is incredibly simple.

Retrieve All Records

To fetch all records from a table, use the all() method:




CODE
$posts = Post::all();  
foreach ($posts as $post) {
echo $post->title;
}






Retrieve a Single Record

You can fetch a single record using the find() method with a primary key:




CODE
$post = Post::find(1); 
echo $post->title;






Alternatively, use the first() method to retrieve the first matching record:




CODE
$post = Post::where('title', 'First Post')->first();  






Use Filters and Conditions

Eloquent allows you to filter results with the where() method:




CODE
$posts = Post::where('title', 'like', '%Laravel%')->get();  









4. Inserting Data with Eloquent



Eloquent simplifies the process of adding new records to your database.

Mass Assignment with Create Method

To use mass assignment, define the fillable property in your model to specify the fields that can be mass-assigned:




CODE
class Post extends Model  
{
protected $fillable = ['title', 'body'];
}






Now you can create a new record like this:




CODE
Post::create([  
'title' => 'New Post',
'body' => 'This is the body of the new post.',
]);






Using the Save Method

Another way to add data is by creating a model instance and saving it:




CODE
$post = new Post();  
$post->title = 'Another Post';
$post->body = 'This is another post body.';
$post->save();









5. Updating Data with Eloquent



Find and Update

To update a record, fetch it first, then modify and save it:




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






Direct Update Method

If you don’t need to fetch the record first, use the update() method:




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









6. Deleting Data with Eloquent



Deleting a Record

To delete a specific record, find it first, then call the delete() method:




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






Bulk Deletion

To delete multiple records based on a condition, use the where() method followed by delete():




CODE
Post::where('title', 'Old Post')->delete();









7. Eloquent Relationships



Eloquent supports relationships, making it easy to manage associations between tables.

One-to-One

A one-to-one relationship links one record in a table to one record in another.




CODE
// User model  
public function profile()
{
return $this->hasOne(Profile::class);
}






Fetch the profile of a user:




CODE
$user = User::find(1);  
$profile = $user->profile;






One-to-Many

A one-to-many relationship links one record in a table to multiple records in another.




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






Fetch all posts for a user:




CODE
$user = User::find(1);  
$posts = $user->posts;






Many-to-Many

A many-to-many relationship links records in one table to many records in another.




CODE
// Post model  
public function tags()
{
return $this->belongsToMany(Tag::class);
}






Attach tags to a post:




CODE
$post = Post::find(1);  
$post->tags()->attach([1, 2]);









8. Query Scopes



Query scopes allow you to reuse query logic.

Defining a Query Scope

Add a scope method to your model:




CODE
public function scopePopular($query)  
{
return $query->where('views', '>', 100);
}
Using a Scope
$popularPosts = Post::popular()->get();









9. Eloquent Events



Eloquent events let you perform actions during a model’s lifecycle.

Using Events

For example, automatically generate a slug when creating a post:

protected static function booted()




CODE
{  
static::creating(function ($post) {
$post->slug = Str::slug($post->title);
});
}









10. Best Practices for Eloquent ORM




  • Use Fillable Fields: Always define the fillable property to avoid mass assignment vulnerabilities.

  • Eager Load Relationships: Use with()to load related models in fewer queries.

  • Optimize Queries: Use scopes, caching, and indexingfor better performance.

  • Validate Inputs: Always validatedata before saving it to the database.






Conclusion



Eloquent ORM is a powerful and flexible tool for managing databases in Laravel. It simplifies common tasks like querying, inserting, updating, and deleting records while supporting advanced features like relationships and events. By mastering Eloquent, you can make your Laravel development faster and more efficient.

Try these examples in your next project to see how Eloquent can transform the way you handle database management.

Vollständiger Original-Bericht
Ausführliche Details, Code-Beispiele & Hersteller-Stellungnahme auf dev.to.
↗ Original-Artikel auf dev.to lesen
Wie bewertest du diesen Beitrag?
1 Klick Feedback
Teilen mit Netzwerk & Team:

Community-Analysen & Experten-Meinungen 0

Verfasse deine eigene Analyse, teile Workarounds oder diskutiere diesen Vorfall im Blog.
Noch keine Community-Analyse verfasst. Markiere einen Textabschnitt oder klicke oben auf Eigene Analyse verfassen“!
Community Pulse: Relevanz-Einschätzung
1 Klick Experten-Votum
🔴 Akute Relevanz 0%
🟡 In Evaluierung 0%
🟢 Keine Auswirkung 0%
Spannende Innovation 0%
Verwandte Story-Cluster & Quellen (Vektor-KI)
Port 8095 Engine
3 Quellen
GPT-6 Astra Release Today? OpenAI’s Next Major AI Model Is Almost Here
1 Quelle
Apple accuses OpenAI of destroying evidence as trade-secrets fight intensifies
1 Quelle
Major AI platforms go down in unprecedented simultaneous outage
Ähnliche Beiträge
🔍 Verwandte News

Auch interessante Nachrichten How to Use Eloquent ORM for Database Management in Laravel

Thematisch verwandte Begriffe: Eloquent, Database, Management, Laravel · 6 Treffer

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...