Laravel Eloquent: CRUD Example

Updated: January 17, 2024 By: Guest Contributor Post a comment

Introduction

Welcome to this Laravel Eloquent CRUD example tutorial. In this guide, we’ll dive deep into how to use Eloquent, Laravel’s own ORM (Object-Relational Mapper), to interact with your database using a rich and fluent syntax. We’ll cover the basics of Create, Read, Update, and Delete (CRUD) operations using practical examples.

Assuming you have a basic understanding of Laravel and have it installed on your system, let’s get started by setting up a new project or navigating to your existing project directory.

Setting Up the Environment

$ composer create-project --prefer-dist laravel/laravel laravel-crud
$ cd laravel-crud

Make sure you have your database settings correct in your .env file.

Creating a Model

To begin, we need a model to work with:

$ php artisan make:model Post -m

The “-m” flag additionally creates a database migration for our Post model. Let’s define some fields in the migration file located at database/migrations:

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

Migrating the Database

After defining the fields, run the migration:

$ php artisan migrate

Create (Store Data)

To create a new post:

$post = new Post();
$post->title = 'Example Post Title';
$post->content = 'This is the content of the post.';
$post->save();

You could also use the create method after defining fillable attributes in your model:

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

// ...later

Post::create([
    'title' => 'Example Post Title',
    'content' => 'Content of the post.'
]);

Read (Retrieve Data)

To retrieve posts:

$posts = Post::all();

To get a single post by id:

$post = Post::find(1);

With conditional:

$post = Post::where('title', 'Example Post Title')->first();

Update (Modify Data)

To update a post:

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

Delete (Remove Data)

To delete a post:

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

For mass deletion:

Post::destroy([1,2,3]);

CRUD with Resource Controller

The process can be streamlined by generating a resource controller:

$ php artisan make:controller PostController --resource

This generates a controller pre-filled with methods mapped to the basic CRUD operations. You can then define the logic within these methods and create routes to handle each action:

Route::resource('posts', 'PostController');

Inside the PostController, you’ll implement methods like index(), create(), store(), show(), edit(), update(), and destroy().

Best Practices and Eloquent Relationships

Eloquent also provides clean methods for defining relationships like hasOne, belongsTo, hasMany, and belongsToMany. Setting up proper relationships allows for more intuitive and concise interactions with your data.

See also:

Conclusion

By now, you should have a good grasp on doing basic CRUD operations using Laravel Eloquent. While this is just the beginning, Laravel and Eloquent provide a rich set of functionalities to help you elegantly work with your database, enhancing the productivity and maintainability of your application. Keep experimenting, and remember to consult the Laravel documentation should you need more complex solutions or additional help.