The Eloquent ORM — Laravel 10 Discovery Training

In this new chapter where we will discover together how to communicate with a database with Laravel and its ORM Eloquent. An ORM, if you’ve never heard of it, is short for Object Rrelational Mapping, these are classes that will allow us to interact with data in the database and that will allow them to be represented in the form of an object. As you will see, it is rather simple to use once you understand the principle.

To begin, you will have to configure the database you want to use. In our case we will use the simplest database to configure: SQLite (Laravel supports MySQL, MariaDB, PostgreSQL and SQL Server). To set up SQLite, we will modify the environment file (the .env file) and at the level of the part DB_CONNECTIONwe will put “sqlite” and we will remove the other information.

Migration

In our case, we want to be able to interact with our database to create a system of articles. We will have to start by creating the table and the various fields necessary and we will not necessarily need to use SQL. We can use the Laravel migration system. To do this, we will go to the terminal and type the command:

php artisan make migration CreatePostTable

This will create a migration file in the folder database/migration which will allow us to add information to our database. The migration file will contain two methods, one method up which explains how to generate the table and the fields and a method down which will allow you to go back.

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->string('slug')->unique();
            $table->longText('content');
            $table->timestamps();
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('posts');
    }
};

This migration system makes it possible to interact with the creation of tables with a PHP API rather than having to write SQL. This adapts to whatever database management system you use.

Once we are satisfied, we will be able to start our migration. To do this, once again, you will have to go to the terminal and type the command

php artisan migrate

If we then look at the content of this database, we will see that there are indeed our different tables, and we have the table posts which will contain the fields that we requested.

The models

Now that our table is created we would like to be able to create, read and modify records. This is where a second component comes in, the “Models”. As with migrations, they can be generated from the command line, by doing a php artisan make:modeland we will call the model Post.

php artisan make:model Post

The name of the model will correspond to the name of the table in the singular. This command will create a file app/Models/Post.php. In this file, we will have few things in the end.

<?php
namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    use HasFactory;
}

It will extend from the Model class which comes from the Eloquent namespace. (this is the name of the ORM that is used by Laravel).

Create an article

With this class we have the possibility to initialize a new article by doing

$post = new Post();

Then I can fill in information on it. This object will have properties that will correspond to the name of the fields in our database.

$post->title="Mon titre";
$post->slug = 'mon-titre';
$post->content="Mon contenu";

Once you have filled this object, you can decide to save it in the database using the method save().

$post->save();

This method is available directly at the level of all the models, and it allows the information to be saved in the database.

Retrieve Items

So in addition to being able to create articles, we will be able to use this model Post to retrieve information. I would like, for example, to recover all the articles from my database. In this case, we will use static methods on our Post class.

$posts = Post::all();

I can also specify the fields I want to use. For example, I can tell him that I am interested only by the ID and the title of the article.

$posts = Post::all(['title', 'id'])

In this case, it will only retrieve this information. If you need to look at what an object looks like, you have a pretty handy little method called ddlike “die and debug”, which allows you to debug a variable.

dd($posts);

If we do a dd of postswe see that my method all()here it refers to something of type Collection, and inside this collection we have our elements in a property items. Each item in my collection is an object of type Post, which is initialized with information from the database. When using methods, it will do what is called hydration, and create objects corresponding to the requested type and fill them with information from the database (We will go into a little more depth on what happens internally later).

In addition to the method all()you also have other interesting methods such as the find method which allows you to retrieve an element from its ID.

$post = Post::find(3);

If I ask it to retrieve a record that does not exist it will return null. You also have another method called findOrFail() which, rather than returning null, will throw an Exception if the data was not found.

$post = Post::findOrFail(3);

This error will be automatically captured by Laravel which will generate a 404 error page.

You can use paginate() which returns the records by paging them.

$posts = Post::paginate(25);

In return, this function will return a LengthAwarePaginator. It is an object that can be used both in views but also in the API part to generate paginations.

  • As part of an API, if we return this object in a controller, Laravel will return a JSON containing the elements, but also the information associated with the pagination.
  • In the context of an HTML application, we can loop over the articles later and we can also use the method links() which will generate the HTML code for the pagination.

This pagination system will also be automatically influenced by the “?page” parameter in the URL which will allow browsing from page to page.

Finally, to finish talking about the retrieval of information, you have the possibility of using the Query Builder system which will allow you to design queries. You can design specific queries starting from the model with methods that will correspond to the verbs used at the SQL level.

$posts = Post::where('created_at', '<', now())
    ->orderBy('created_at', 'desc')
    ->get();

Create

To create a new record, you can use the method create() passing it the values ​​of the various fields.

$post = Post::create([
    'title' => 'Mon Titre',
    'slug'  => 'mon-titre',
    'online'=> true
])

However this method is secure by default in Laravel which will not let you use any fields in this method. You must define all the “fillable” fields through a property fillable in the model.

class Post {

    protected $fillable = ['title', 'slug', 'online'];

}

In the same way, we have a property which represents the inverted notion guardedwhich allows you to define fields that are not fillable.

Edit

If you want to modify an article, the first approach, which is quite simple, is to retrieve a record and then modify its properties.

$post = Post::find(3);
$post->title="Mon nouveau titre";
$post->save();

It is also possible to modify several records from a query.

$post = Post::where('online', false)->update([
    'online' => true
])

DELETE

Finally, to delete a record, just use the method delete().

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

But as for the update, we can use this method from a query to delete several records.