Sling Academy
Home/PHP/Can you use Eloquent ORM without Laravel?

Can you use Eloquent ORM without Laravel?

Last updated: January 17, 2024

Introduction

Eloquent ORM is a powerful Object-Relational Mapper designed for Laravel, but what if you want to use it without the full Laravel framework? Luckily, Eloquent can be implemented as a standalone package. In this tutorial, we’ll explore how to use Eloquent outside of Laravel with plenty of code examples.

Setting up the Environment

To begin using Eloquent by itself, you need to create a new project and set up Composer. If you don’t have Composer installed, see one of the following articles:

Set up example project:

mkdir eloquent_standalone
cd eloquent_standalone
composer init

Next, add Eloquent as a dependency:

composer require illuminate/database

Once installed, bootstrap Eloquent:

use Illuminate\Database\Capsule\Manager as Capsule;

$capsule = new Capsule;
$capsule->addConnection([
  'driver'    => 'mysql',
  'host'      => 'localhost',
  'database'  => 'your_database',
  'username'  => 'your_username',
  'password'  => 'your_password',
  'charset'   => 'utf8',
  'collation' => 'utf8_unicode_ci',
  'prefix'    => '',
]);

$capsule->bootEloquent();

Defining Models

With Eloquent bootstrapped, define models that extend Illuminate\Database\Eloquent\Model:

use Illuminate\Database\Eloquent\Model;

class User extends Model {}

class Post extends Model {}

These models will automatically map to the tables users and posts in the database.

Basic Operations

Creating Records

$user = new User();
$user->name = 'John Doe';
$user->email = '[email protected]';
$user->save();

// Output
echo $user->id; // The ID of the newly created user

Reading Records

$users = User::where('name', 'John Doe')->get();

// Output
foreach ($users as $user) {
  echo $user->email;
}

Updating Records

$user = User::find(1);
$user->email = '[email protected]';
$user->save();

Deleting Records

$user = User::find(1);
$user->delete();

Advanced Features

Relationships

Define relationships directly within your models:

class Post extends Model {
  public function user() {
    return $this->belongsTo('User');
  }
}

Use relationships to retrieve related records:

$post = Post::find(1);
$user = $post->user;
// Output
echo $user->name;

Mass Assignment

Using the create method:

User::create(['name' => 'Jane Doe', 'email' => '[email protected]']);

Accessors & Mutators

To automatically apply formatting to model attributes use accessors and mutators:

class User extends Model {
  public function getNameAttribute($value) {
    return ucfirst($value);
  }
  public function setNameAttribute($value) {
    $this->attributes['name'] = strtolower($value);
  }
}

In the example above, the user’s name is stored in lowercase but retrieved with the first letter capitalized.

Conclusion

As demonstrated, Eloquent can be a versatile ORM even outside Laravel. With these foundations, you can integrate it within other projects or micro-frameworks, taking advantage of its expressive syntax and powerful features.

Next Article: Using belongsTo() and hasMany() in Laravel Eloquent

Previous Article: Using ‘UNION’ in Laravel Eloquent

Series: Laravel & Eloquent Tutorials

PHP

You May Also Like

  • Pandas DataFrame.value_counts() method: Explained with examples
  • Constructor Property Promotion in PHP: Tutorial & Examples
  • Understanding mixed types in PHP (5 examples)
  • Union Types in PHP: A practical guide (5 examples)
  • PHP: How to implement type checking in a function (PHP 8+)
  • Symfony + Doctrine: Implementing cursor-based pagination
  • Laravel + Eloquent: How to Group Data by Multiple Columns
  • PHP: How to convert CSV data to HTML tables
  • Using ‘never’ return type in PHP (PHP 8.1+)
  • Nullable (Optional) Types in PHP: A practical guide (5 examples)
  • Explore Attributes (Annotations) in Modern PHP (5 examples)
  • An introduction to WeakMap in PHP (6 examples)
  • Type Declarations for Class Properties in PHP (5 examples)
  • Static Return Type in PHP: Explained with examples
  • PHP: Using DocBlock comments to annotate variables
  • PHP: How to ping a server/website and get the response time
  • PHP: 3 Ways to Get City/Country from IP Address
  • PHP: How to find the mode(s) of an array (4 examples)
  • PHP: Calculate standard deviation & variance of an array