Laravel Eloquent ORM

Lesson 24 of 50 - Learn how to interact with database records using Laravel Eloquent ORM.

48%
1. What Is Eloquent ORM?

Eloquent ORM is Laravel's Object-Relational Mapper. It allows you to work with database tables using PHP model classes instead of writing SQL queries for every operation.

For example, you can use Eloquent to:

  • Insert student records.
  • Retrieve records from a database.
  • Update existing records.
  • Delete records.
  • Define relationships between tables.

Without Eloquent, you might write a query like:

SELECT * FROM students;

Using Eloquent, you can write:

Student::all();

Eloquent makes database operations easier to read and maintain.

2. Create an Eloquent Model

A model represents a database table. By convention, Laravel expects the Student model to use the students table.

Create a model using Artisan:

php artisan make:model Student

Laravel creates the file app/Models/Student.php.

<?php

namespace App\Models;

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

class Student extends Model
{
    use HasFactory;
}

The model inherits database functionality from Laravel's Model class.

The HasFactory trait allows you to use model factories to generate sample student records.

3. Retrieve All Records

Use the all() method to retrieve all records from a model's table.

use App\Models\Student;
use Illuminate\Support\Facades\Route;

Route::get('/students', function () {

    $students = Student::all();

    return response()->json($students);
});

Laravel retrieves all student records and returns them as a JSON response.

This example assumes that the students table already exists. For large tables, use pagination rather than retrieving every record at once.

4. Retrieve a Single Record

Use find() to retrieve a record by its primary key.

$student = Student::find(1);

If a student with ID 1 exists, Laravel returns the corresponding model. Otherwise, it returns null.

You can also use findOrFail():

$student = Student::findOrFail(1);

If the record does not exist, Laravel throws a model-not-found exception, which normally results in a 404 response in an HTTP request.

Example route:

Route::get('/students/{id}', function ($id) {

    $student = Student::findOrFail($id);

    return response()->json($student);
});
5. Insert a New Record

You can insert a record using the model's create() method after configuring mass assignment.

Update app/Models/Student.php:

<?php

namespace App\Models;

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

class Student extends Model
{
    use HasFactory;

    protected $fillable = [
        'name',
        'email',
        'course',
    ];
}

Insert a student:

$student = Student::create([
    'name' => 'Rahul Kumar',
    'email' => 'rahul@example.com',
    'course' => 'Web Development',
]);

The $fillable property specifies which attributes can be assigned through mass-assignment methods such as create().

Only include fields that users or application code are allowed to set. The database table must contain the corresponding columns.

6. Update an Existing Record

Retrieve a model, change its attributes, and call save() to update the database record.

$student = Student::findOrFail(1);

$student->name = 'Amit Kumar';
$student->course = 'Python';

$student->save();

You can also update records using the update() method.

$student = Student::findOrFail(1);

$student->update([
    'name' => 'Amit Kumar',
    'course' => 'Python',
]);

The update() method uses mass assignment, so the fields must be allowed by the model's $fillable or $guarded configuration.

7. Delete a Record

You can delete a record by retrieving the model and calling delete().

$student = Student::findOrFail(1);

$student->delete();

You can also delete a record directly by its primary key:

Student::destroy(1);

To delete several records by their IDs:

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

These operations delete matching records from the database. Use authorization checks before allowing users to delete records.

8. Filter and Sort Records

Eloquent supports query methods for filtering, ordering, and limiting database results.

Find students enrolled in Python:

$students = Student::where(
    'course',
    'Python'
)->get();

Find one student by email:

$student = Student::where(
    'email',
    'rahul@example.com'
)->first();

Sort students by name:

$students = Student::orderBy(
    'name',
    'asc'
)->get();

Retrieve the first five records:

$students = Student::orderBy('id')
    ->limit(5)
    ->get();

The get() method returns a collection of matching models, while first() returns one model or null.

9. Eloquent Methods and Practical Assignment

Important Eloquent methods:

Method Purpose
all() Retrieve all records.
find() Find a record by primary key.
findOrFail() Find a record or throw a not-found exception.
create() Create and save a record using mass assignment.
save() Persist changes to a model.
update() Update model attributes.
delete() Delete a model record.
where() Filter records by conditions.

Practical Assignment:

  1. Create a Student model using Artisan.
  2. Connect it to an existing students table.
  3. Retrieve all students and return them as JSON.
  4. Find a student by ID.
  5. Insert a student using create() and $fillable.
  6. Update a student's name and course.
  7. Delete a test student record.
  8. Filter students by course and sort them by name.

Test database changes using a development database, and avoid exposing private student information through public routes.

Quick Quiz

1. What does Eloquent ORM help you do?




2. Which method retrieves a record by its primary key?




3. Which method deletes a retrieved model record?