How To Use Laravel 11 Eloquent For Database Interactions

Laravel 11’s Eloquent ORM (Object-Relational Mapping) provides a simple and elegant way to interact with your database. It allows you to perform CRUD (Create, Read, Update, Delete) operations without writing complex SQL queries. Here’s how you can use Laravel 11 Eloquent for database interactions.

Setting Up Eloquent

First, ensure you have a Laravel project set up. If not, you can create one using Composer:

composer create-project --prefer-dist laravel/laravel myProject

Next, configure your database settings in the .env file located in the root directory of your Laravel project. Update the following lines with your database credentials:

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

Creating a Model

Models in Laravel represent a table in your database. 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. You can also create a migration file along with the model by using the -m flag:

php artisan make:model Post -m

Defining the Table Schema

Edit the migration file located in database/migrations to define the schema of the posts table:

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

Run the migration to create the table:

php artisan migrate

Performing CRUD Operations

Creating Records

To insert a new record into the posts table:

use App\Models\Post;

$post = new Post();
$post->title = 'My First Post';
$post->content = 'This is the content of my first post.';
$post->save();

Alternatively, you can use the create method, but make sure to define the fillable properties in your model to prevent mass assignment vulnerabilities:

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

Post::create([
    'title' => 'My Second Post',
    'content' => 'This is the content of my second post.',
]);

Reading Records

To retrieve all records from the posts table:

$posts = Post::all();

To retrieve a single record by its primary key:

$post = Post::find(1);

To use more specific queries, you can use methods like where:

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

Updating Records

To update a record, retrieve it first, make the necessary changes, and then save it:

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

Deleting Records

To delete a record, retrieve it and call the delete method:

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

You can also delete records using a query:

Post::where('title', 'Updated Title')->delete();

Advanced Features

Eloquent provides many advanced features such as relationships, eager loading, accessors and mutators, and scopes. For instance, defining a one-to-many relationship between User and Post models:

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

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

Conclusion

Laravel 11’s Eloquent ORM simplifies database interactions, making it easier to manage and manipulate data within your application. By following these steps, you can efficiently use Eloquent for CRUD operations and take advantage of its powerful features to build robust and maintainable applications.

Leave a Reply