Eloquent ORM

<aside> 💡

ORM (Object-Relational Mapper)

An ORM is a tool that allows interaction with a database using code instead of raw SQL queries. It converts database tables into objects, making it easier to create, read, update, and delete records using programming languages. The ORM used in Laravel is called Eloquent

</aside>

Eloquent Documentations

Eloquent: Getting Started - Laravel 12.x - The PHP Framework For Web Artisans

Using Eloquent to Get Data From Database

Using Tinker

<aside> 💡

Collections

In Eloquent ORM, collections provide a convenient way to work with multiple Eloquent models. When methods like get() or all() are used, Eloquent returns a collection instead of a simple array.

Eloquent collections extend Laravel's base Collection class and they have methods such as filter(), map(), pluck(), each(), etc.

Example:

$users = User::where('active', true)->get(); // Returns a collection

$names = $users->pluck('name'); // Extracts only the 'name' field

$filteredUsers = $users->filter(fn($user) => $user->age > 25); // Filters users older than 25

</aside>

php artisan tinker
use App\\Models\\Book;

Book::all()

Using Route and Returning JSON

<aside> 💡

JSON

JSON (JavaScript Object Notation) is a lightweight data format used to store and exchange data. JSON represents data as key-value pairs, similar to a JavaScript object, and is commonly used in APIs

</aside>

<?php

use Illuminate\\Support\\Facades\\Route;

Route::get('/books', function () {
    $a = Book::all();
    return $a;
});
[
  {
    "id": 1,
    "publication_year": "2020",
    "title": "Laravel Programming",
    "created_at": "2025-02-24T08:32:22.000000Z",
    "updated_at": "2025-02-24T08:32:22.000000Z"
  },
  {
    "id": 2,
    "publication_year": "2021",
    "title": "C++ Programming",
    "created_at": "2025-02-24T08:32:22.000000Z",
    "updated_at": "2025-02-24T08:32:22.000000Z"
  },
  {
    "id": 3,
    "publication_year": "2026",
    "title": "Javascript Programming",
    "created_at": "2025-03-01T05:57:04.000000Z",
    "updated_at": "2025-03-01T05:57:04.000000Z"
  }
]

Using a View with Blade

<aside> 💡

Blade is the templating language used for PHP

</aside>

<?php

use Illuminate\\Support\\Facades\\Route;

Route::get('/books', function () {
    $books = Book::all();
    return view('books', ['books' => $books]);
});

<aside> 💡

Paths are separated by . when returning a view

</aside>

<aside> 💡

To pass data to a view use an associative array as the second parameter to the view function

</aside>

<h2> The List of all Books: </h2>

@foreach ($books as $book)
	<p>{{ $loop->index+1 }}- {{ $book->title }}</p>
@endforeach

<aside> 💡

Blade Syntax

Blade Templates - Laravel 12.x - The PHP Framework For Web Artisans

<aside> 📌

Examples:

</aside>