Getting Started With Eloquent ORM in Laravel

  • Home
  • Laravel
  • Getting Started With Eloquent ORM in Laravel
Front
Back
Right
Left
Top
Bottom
LARAVEL vs AI
Sanjeewa%20RupasingheIntroduction

Why Eloquent ORM?

If you've ever wondered how modern web applications handle data seamlessly, the answer often lies in the Object-Relational Mapping (ORM) tool they use. Laravel's Eloquent ORM is one of the most powerful, readable, and flexible in PHP web development. Whether you're a student, a CTO, or an entrepreneur wanting robust applications for your business, mastering Eloquent can vastly improve your workflow and simplify data management.1
SETTING UP

Setting Up Eloquent in Laravel

First things first: Eloquent comes pre-integrated with Laravel. When you create a new Laravel project, Eloquent is ready to go. Here’s a quick setup2 After connecting the database, you’re ready for your first model!
Copy to clipboard
// bash
// create laravel app
composer create-project laravel/laravel blogapp

// .env
DB_CONNECTION=mysql
// sqlite | mysql | mariadb | pgsql | sqlsrv
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=database_name
DB_USERNAME=database_user
DB_PASSWORD=database_password
MODEL

Eloquent Model Creation and Migration

Models are the backbone of Eloquent. They represent the data tables of your application
Post.php
Copy to clipboard
// php artisan make:model Post -mrRfs
// -m: Creates a migration file for the model
// -r: Creates a resource controller
// R: Creates a resource route in routes
// f: Creates a factory for the model
// s: Creates a seeder for the model

// app/Models/Post.php
// represents a database table and allows you to interact with its data using object-oriented code instead of raw SQL
class Post extends Model
{
    use HasFactory;
    
    // Mass assignment lets you insert or update multiple model attributes in a single line, boosting productivity and code clarity.
    protected $fillable = ['title', 'content'];
    
    // Mass assignment for all the columns
    // protected $guarded = [];
}

// database/migrations/xxxx_xx_xx_create_posts_table.php
// used to define and change your database structure (like creating tables and columns) in code so everyone on the team can keep the same database version
// migration versions handle by timestamps {timestamps}_{migration_name}
Schema::create('posts', function (Blueprint $table) {
      $table->id();
      $table->string('title');
      $table->text('content');
      $table->timestamps();
});

// database/factories/PostFactory.php
// used to automatically generate fake data for a model, often used for testing or seeding the database with sample records
public function definition(): array
{
    return [
        'title'   => fake()->sentence(6),
        'content' => fake()->paragraph(10),
    ];
}

// database/seeders/PostSeeder.php
// inserts sample or default data into the database, helping you quickly populate tables for development or testing.
public function run(): void
{
    Post::factory()
        ->count(100)
        ->create();
}
Show more Show less
CRUD

Performing CRUD Operations with Eloquent

Eloquent reads just like English, making code easy for teams to maintain and scale. Here are CRUD (Create, Read, Update, Delete) basics3
File icon
SendReportMail.php
Copy to clipboard
<?php

namespace App\Http\Controllers;

use App\Models\Post;
use App\Http\Requests\StorePostRequest;
use App\Http\Requests\UpdatePostRequest;
use Illuminate\Http\JsonResponse;

class PostController extends Controller
{

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function index(): JsonResponse
    {
        $posts = Post::all();

        return response()->json(
            [
                'status' => 'success',
                'data'   => $posts
            ],
            200
        );
    }

    /**
     * Store a newly created resource in storage.
     * 'title'   => 'required',
     * 'content' => 'required',
     *
     * @param  \App\Http\Requests\StorePostRequest  $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function store(StorePostRequest $request): JsonResponse
    {
        $post = Post::create($request->all());

        return response()->json(
            [
                'status' => 'success',
                'data'   => $post
            ],
            201
        );
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\Post  $post
     * @return \Illuminate\Http\JsonResponse
     */
    public function show(Post $post): JsonResponse
    {
        return response()->json(
            [
                'status' => 'success',
                'data'   => $post
            ],
            200
        );
    }

    /**
     * Update the specified resource in storage.
     * 'title'   => 'required',
     * 'content' => 'required',
     *
     * @param  \App\Http\Requests\UpdatePostRequest  $request
     * @param  \App\Models\Post  $post
     * @return \Illuminate\Http\JsonResponse
     */
    public function update(UpdatePostRequest $request, Post $post): JsonResponse
    {
        $post->update($request->all());

        return response()->json(
            [
                'status' => 'success',
                'data'   => $post
            ],
            200
        );
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\Post  $post
     * @return \Illuminate\Http\JsonResponse
     */
    public function destroy(Post $post): JsonResponse
    {
        $post->delete();

        return response()->json(
            [
                'status' => 'success',
                'data'   => $post
            ],
            200
        );
    }
}
Show more Show less

Explore project snapshots or discuss custom web solutions.

SUMMARY

Summary & Professional Takeaway

Laravel’s Eloquent ORM is your ally for rapid, scalable, and maintainable web development. Whether streamlining a sales dashboard, powering a blog, or scaling a global business, its readable syntax and robust features empower both IT professionals and business leaders to succeed.

Simplicity is the ultimate sophistication

Leonardo da Vinci

Thank You for Spending Your Valuable Time

I truly appreciate you taking the time to read blog. Your valuable time means a lot to me, and I hope you found the content insightful and engaging!
Front
Back
Right
Left
Top
Bottom
FAQ's

Frequently Asked Questions

No, Eloquent ships with Laravel by default.

Always define the `$fillable` property in your models.

Yes, but for high performance, use chunking (`chunk()`), lazy collections, or raw queries as needed.

Check:https://laravel.com/docs/12.x/migrations

Eloquent is tightly coupled with Laravel, but it can be used standalone with effort.

  1. Available at:https://laravel.com/docs/12.x/eloquent
  2. Available at:https://laravel.com/docs/12.x/database
  3. Available at:https://laravel.com/docs/12.x/migrations

Comments are closed