Mastering Laravel’s Eloquent ORM: A Comprehensive Guide with Sample Code
Laravel’s Eloquent ORM (Object-Relational Mapping) simplifies database interactions by abstracting database tables into PHP objects, enabling developers to work with data more intuitively. In this article, we’ll explore Eloquent ORM and provide a complete, runnable example using a PostgreSQL database. We’ll connect to a database and interact with a documents
table.
Setting Up a New Laravel Project
First, ensure you have Composer installed on your machine. You can install Laravel by running the following command:
composer create-project --prefer-dist laravel/laravel document_platform
This command creates a new Laravel project named document_platform
.
Navigate to the project directory:
cd document_platform
Install PDO PostgreSQL Driver (if needed)
If the PDO PostgreSQL driver (pdo_pgsql
) is not installed, you'll need to install it using the package manager for your operating system. For Ubuntu, you can typically install it with:
Ubuntu
sudo apt-get install php-pgsql
Mac
brew install php@8.1-pgsql
Windows
- Using XAMPP / WampServer / Other PHP Distributions:
- For XAMPP: Locate your
php.ini
file (typicallyxampp\php\php.ini
), and uncomment or add the following lines:
extension=pdo_pgsql extension=pgsql
- For WampServer: Navigate to
php.ini
(usuallywamp\bin\php\php{version}\php.ini
), and make the same modifications as above. - Restart Apache:
- Restart Apache through the XAMPP / WampServer control panel to apply the changes.
Setting Up the Database Connection
First, configure your Laravel application to connect to your PostgreSQL database. Open the .env
file and add the following database connection details. In your case you may adjust the following information per your database connection info.
DB_CONNECTION=pgsql
DB_HOST=192.168.3.187
DB_PORT=5432
DB_DATABASE=document_platform_db
DB_USERNAME=postgres
DB_PASSWORD=zuruck
the database we connect above, has a table named documents with the following structure:
you may create your own if you dont have.
Creating the Model and Migration
Next, create a model and migration for the documents
table. Run the following Artisan command:
php artisan make:model Document
This command creates a Document
model. Since we already have the table we dont use -m param to generate a migration file.
Defining the Model
Open the Document
model located in app/Models/Document.php
and define the fillable attributes:
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Document extends Model
{
use HasFactory;
protected $fillable = [
'title',
'description',
'author_id',
'price',
'file_path',
];
public function author()
{
return $this->belongsTo(User::class, 'author_id');
}
}
Creating a Controller
Create a controller to handle CRUD operations:
php artisan make:controller DocumentController
Open app/Http/Controllers/DocumentController.php
and implement basic CRUD methods:
namespace App\Http\Controllers;
use App\Models\Document;
use Illuminate\Http\Request;
class DocumentController extends Controller
{
public function index()
{
$documents = Document::all();
return response()->json($documents);
}
public function show($id)
{
$document = Document::find($id);
return response()->json($document);
}
public function store(Request $request)
{
$document = Document::create($request->all());
return response()->json($document, 201);
}
public function update(Request $request, $id)
{
$document = Document::find($id);
$document->update($request->all());
return response()->json($document);
}
public function destroy($id)
{
$document = Document::find($id);
$document->delete();
return response()->json(null, 204);
}
}
Setting Up Routes
Define routes for the DocumentController in routes/api.php
:
use App\Http\Controllers\DocumentController;
Route::apiResource('documents', DocumentController::class);
Testing the API
Use a tool like Postman or cURL to test the API endpoints:
- GET /api/documents: Retrieve all documents.
- GET /api/documents/{id}: Retrieve a specific document.
- POST /api/documents: Create a new document.
- PUT /api/documents/{id}: Update an existing document.
- DELETE /api/documents/{id}: Delete a document.
Example cURL command to create a document:
curl -X POST http://localhost:8000/api/documents \
-H "Content-Type: application/json" \
-d '{"title":"Sample Document","description":"This is a sample document.","author_id":1,"price":99.99,"file_path":"/path/to/file.pdf"}'
Conclusion
By following these steps, you’ve set up a complete Laravel application using Eloquent ORM to interact with a PostgreSQL database. This example demonstrates the power and simplicity of Eloquent ORM for managing database operations, enabling you to build robust web applications with ease. Explore further, experiment with advanced Eloquent features, and unlock the full potential of Laravel’s ORM capabilities.