Laravel Eloquent ORM Basics

Laravel ~ 8 minutes

# Welcome to Eloquent

Hello and welcome! In this tutorial, we will learn Eloquent, the database tool that comes with Laravel. Eloquent is an ORM. ORM means Object Relational Mapper. It sounds big, but the idea is very simple.

With Eloquent, one database table becomes one PHP class. One row in the table becomes one object. So you can work with your data using normal PHP code, and you do not need to write long SQL queries by hand.

What you will learn today

  • How to create a model and a migration
  • How to create, read, update and delete rows
  • How to use simple query methods
  • How to connect two models with a relationship

Do not worry if you are new to this. We will go step by step, and every step is small. Please keep a Laravel project ready and let us start. You can read more in the official Eloquent docs at any time.

Create a model with a migration
Code Copied to Clipboard

# What this command made

Great! That one command created two files for us. The first file is the model. It lives in the app/Models folder and is named Post.php. The second file is a migration. It lives in the database/migrations folder.

The -m flag means also make a migration. A migration is like a plan for your table. It tells the database which columns the table should have.

By default, Eloquent guesses the table name from the model name. For the model Post, it uses the table posts. It uses the plural form in small letters. This rule is called a convention, and it saves you from a lot of setup work.

Now, please open the new migration file. We will add some columns to it.

Migration: the posts table
Code Copied to Clipboard

# Reading the migration

Let us read this code slowly. The up method runs when we apply the migration. Inside it, Schema::create builds a new table called posts.

Columns we added

  • id() adds a primary key that counts up by itself
  • string('title') adds a short text column
  • text('body') adds a long text column
  • boolean('is_published') adds a true or false column with a default of false
  • timestamps() adds created_at and updated_at

The two timestamp columns are special. Eloquent fills them for you each time you create or change a row. You never need to set them yourself.

Run the migration
Code Copied to Clipboard

# Now the table exists

Very good! Laravel has now built the posts table in your database. If you open your database tool, you will see it there with all the columns we listed.

Next, let us look at the model class. Right now it is almost empty, and that is fine. But there is one thing we must add. Eloquent protects your data from mass assignment. This means that, by default, you cannot fill many fields at once with an array.

This is a safety feature. It stops a bad user from sending extra fields, such as is_admin, in a form. To allow the fields you trust, you list them in a property called $fillable.

The Post model
Code Copied to Clipboard

Fillable or guarded?

You can also use the opposite property, called $guarded. It lists the fields that are not allowed. Many developers prefer $fillable because it is a safe allow list. If you forget a field, nothing bad happens. The field is simply blocked until you add it.

If you see the error Add [title] to fillable property to allow mass assignment, do not panic. It only means you forgot to list that field in $fillable. Add the field name, save the file, and try again.

# Creating rows

Now, please let us save our first post. There are two common ways. The first way is to make a new object, set its fields, and call save. The second way is to call Post::create with an array. The second way is shorter, and it uses the $fillable list we just made.

Both ways give the same result. Use the one you find easier to read. In real projects, the data usually comes from a validated form request, so create is used very often.

Here is the short way.

Create a post
Code Copied to Clipboard

# Reading rows

Next, let us read data back. Eloquent gives us many friendly methods. Here are the ones you will use every day.

Common read methods

  • Post::all() gets every row
  • Post::find(1) gets one row by its id, or null
  • Post::findOrFail(1) gets one row or shows a 404 page
  • Post::where(...)->get() gets rows that match a rule
  • Post::first() gets only the first row

You can chain methods together like building blocks. For example, you can filter, sort, and limit in one line. Each method returns a query builder, until you call get, first or paginate to run the query.

Query examples
Code Copied to Clipboard

# Updating and deleting

Updating is easy too. First, find the row. Then change the fields and call save. You can also call update with an array, and it will save at once.

To remove a row, find it and call delete. You can also use Post::destroy(1) if you only know the id.

Please be careful with delete. It removes the row for good. If you want a safer way, Laravel offers soft deletes. With soft deletes, the row stays in the table, but it is hidden from normal queries. You can restore it later if you change your mind.

Let us see a short example of both actions.

Update and delete
Code Copied to Clipboard
Protect your data

Please remember two important rules when you use Eloquent.

Safety rules

  • Never pass $request->all() to create without validating it first
  • Always keep $fillable as small as possible
  • Use findOrFail when a missing row should be a 404 page

If you skip validation, users may save wrong or harmful data. Read the validation docs and make this a habit from your very first project.

# Relationships

Real apps have more than one table. A user has many posts, and a post belongs to one user. Eloquent lets us describe this with simple methods on the model. These are called relationships.

For this, the posts table needs a user_id column. This column is called a foreign key. Laravel follows the naming rule user_id for the User model, so it finds the link by itself.

Once the relationship is set, you can write $user->posts to get all posts of that user. You can also write $post->user to get the owner of a post. It feels like magic, but it is just a method call behind the scenes.

Define the relationship
Code Copied to Clipboard

Avoid the N+1 problem

When you loop over many posts and read $post->user each time, Laravel runs one extra query for every post. This is called the N+1 problem, and it makes your app slow.

The fix is called eager loading. Use Post::with('user')->get() and Laravel will load all the owners in just one more query. Please remember this trick. It is one of the best speed wins in Laravel.

# Try it in Tinker

The best way to learn is to practice. Laravel gives us a small playground called Tinker. It lets you run PHP and Eloquent code right in your terminal, without making any route or page.

Let us open it now. After it starts, you can type lines such as App\Models\Post::count() and press Enter. You will see the answer at once. Try creating, finding and deleting a few posts to feel how Eloquent works. Please do not be shy to make mistakes here. It is only your practice database.

Start Tinker
Code Copied to Clipboard

# Summary and next steps

Well done! You have finished this tutorial. Let us quickly remember what we learned.

Summary

  • A model maps to one table, and a row maps to one object
  • Migrations build the table, and $fillable allows mass assignment
  • create, find, where, update and delete handle daily work
  • Relationships such as hasMany and belongsTo link your tables
  • Eager loading with with keeps your app fast

What to learn next

  • Query scopes and accessors
  • Soft deletes and model events
  • Many to many relationships

The Eloquent relationships guide is a very good place to continue. Keep practicing, and you will get better every day.