Eloquent ORM - Laravel

Eloquent ORM - Laravel

Relational databases

Since its inception in 2011, Laravel has become one of the most popular PHP frameworks available. Part of the reason for its popularity is its use of the Eloquent object-relational mapper (ORM). Eloquent makes working with relational databases much easier, and it's one of the main reasons Laravel is so popular with developers.

In this article, we'll take a look at what Eloquent is, how it works, and how to use it in your Laravel applications.

What is Eloquent?

Eloquent is an ORM for PHP that makes working with relational databases much easier. It provides a number of features that make it easier to work with databases, including the ability to easily query for data, hydrate it into objects, and save it back to the database. Eloquent also provides a number of helpful methods for working with related data.

How Does Eloquent Work?

Eloquent uses a number of different techniques to make working with databases easier. One of the most important is Active Record. Active Record is a design pattern that provides an object-oriented interface to relational data. This means that instead of working with raw data from the database, you work with objects that have their own methods and properties.

For example, imagine you have a database table for users. With Active Record, you would define a User class that represents a row in that table. Each instance of the User class would represent a specific user from the database. You would then be able to call methods on the User object to insert, update, or delete that user from the database.

Another important part of Eloquent is its ability to lazy load data. Lazy loading is a technique for loading data on demand. This means that when you retrieve an Eloquent model, only the data that you actually need is loaded from the database. Related data is not loaded until you specifically request it.

This can be a huge performance boost, because it means that you only load the data you need, when you need it. It also means that you don't have to worry about writing SQL queries to join data from multiple tables. Eloquent will handle that for you.

How to Use Eloquent

Eloquent is easy to use, and it integrates well with Laravel. Let's take a look at a few examples of how to use Eloquent in a Laravel application. To get started, we need to create a new Laravel project. We can do that with the Laravel CLI tool by running the following command:

$ laravel new blog

This will create a new folder called blog with a fresh Laravel installation.

Next, we need to create a database and connect it to our Laravel project. I'll be using MySQL for this example, but you can use whatever database you like. Once you have a database set up, update your .env file with the database connection details.

With the database set up, we can now create our first Eloquent model. Models in Laravel are stored in the app directory, so we'll create a new file called app/Post.php. The model class should extend the Illuminate\Database\Eloquent\Model class, like this:

namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model {

//

}

This is a very basic model class. It doesn't contain any methods or properties, but it does extend the Model class, which gives it all of the functionality provided by Eloquent.

Next, we need to create a database table to store our posts. We can do that with a Laravel migration. Migrations are stored in the database/migrations directory. To create a new migration, we can use the Laravel CLI tool, like this:

$ php artisan make:migration create_posts_table

This will create a new file called database/migrations/YYYY_MM_DD_HHMMSS_create_posts_table.php. The file will contain a migration class with a up() and a down() method. The up() method is used to make changes to the database, and the down() method is used to undo those changes.

We can add a columns() method to our migration class to define the columns that should be in our posts table. The method should return an array of column names and data types, like this:

public function up() {

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

$table->timestamps(); });

}

public function down() {

Schema::drop('posts'); } public function columns() { return [ 'title' => 'string', 'body' => 'text', ];

}

With our migration defined, we can now run it to create the posts table in the database. We can do that with the Artisan CLI tool, like this:

$ php artisan migrate

Now that we have a database table and a model, we can start querying for data. For example, we can get all of the posts from the database like this:

$posts = App\Post::all();

This will return an Eloquent Collection of Post objects. We can then loop through the collection and access the data on each object, like this:

foreach ($posts as $post) {

echo $post->title;

}

If we only want a single post, we can use the find() method. The find() method accepts an ID as its only argument. It will return the post with that ID, or NULL if no post is found.

$post = App\Post::find(1);

We can also use the first() method to get the first post from the database. The first() method doesn't accept any arguments. It will simply return the first post from the database, or NULL if no posts are found.

$post = App\Post::first();

To create a new post, we can use the create() method. The create() method accepts an array of data to be inserted into the database. The data should be in the same format as the columns() method in the migration.

$post = App\Post::create([ 'title' => 'My First Post', 'body' => 'This is the body of my first post', ]);

This will insert a new row into the database and return the resulting Post object. We can then access the data on the object, or save it back to the database.

$post->title = 'My Updated Post'; $post->save();

To update an existing post, we can use the update() method. The update() method accepts an array of data to be updated. The data should be in the same format as the columns() method in the migration.

$post = App\Post::find(1); $post->update([ 'title' => 'My Updated Post', 'body' => 'This is the updated body of my post', ]);

This will update the row in the database and return the resulting Post object. To delete a post, we can use the delete() method. The delete() method doesn't accept any arguments. It will simply delete the post from the database.

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

This will delete the post with an ID of 1 from the database.

Conclusion In this article, we've looked at what Eloquent is and how it can make working with relational databases much easier. We've also looked at how to use Eloquent in a Laravel application.

Did you find this article valuable?

Support Christopher by becoming a sponsor. Any amount is appreciated!