Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
N

NeoEloquent

> 后端框架
Open source

The Neo4j OGM for Laravel

656 stars0 likes1 views
WebsiteGitHub

About

The Neo4j OGM for Laravel

NeoEloquent

Neo4j Graph Eloquent Driver for Laravel.

Quick Reference

  • Installation
  • Configuration
  • Models
  • Relationships
  • Edges
  • Migration
  • Schema
  • Aggregates
  • Only in Neo
  • Things To Avoid

Installation

Run composer require vinelab/neoeloquent

Or add the package to your composer.json and run composer update.

json
{
    "require": {
        "vinelab/neoeloquent": "1.8.*"
    }
}

Add the service provider in app/config/app.php:

php
Vinelab\NeoEloquent\NeoEloquentServiceProvider::class,

The service provider will register all the required classes for this package and will also alias the Model class to NeoEloquent so you can simply extend NeoEloquent in your models.

Configuration

Connection

in app/config/database.php or in case of an environment-based configuration app/config/[env]/database.php make neo4j your default connection:

php
'default' => 'neo4j',

Add the connection defaults:

php
'connections' => [
    'neo4j' => [
        'driver' => 'neo4j',
        'host'   => 'localhost',
        'port'   => 7687,
        'username' => 'username',
        'password' => 'password',
    ]
]

Remember to update your ENV variables (.env) in case you're using them.

Migration Setup

If you're willing to have migrations:

  • create the folder app/database/labels
  • modify composer.json and add app/database/labels to the classmap array
  • run composer dump-autoload

Documentation

Models

  • Node Labels
  • Soft Deleting
php
use NeoEloquent;

class User extends NeoEloquent {}

As simple as it is, NeoEloquent will generate the default node label from the class name, in this case it will be :User. Read about node labels here

Namespaced Models

When you use namespaces with your models the label will consider the full namespace.

php
namespace App\Models;

use NeoEloquent;

class Admin extends NeoEloquent { }

The generated label from that relationship will be VinelabCmsAdmin, this is necessary to make sure that labels do not clash in cases where we introduce another Admin instance like Vinelab\Blog\Admin then things gets messy with :Admin in the database.

Custom Node Labels

You may specify the label(s) you wish to be used instead of the default generated, they are also case sensitive so they will be stored as put here.

php
use NeoEloquent;

class User extends NeoEloquent {

    protected $label = 'User'; // or array('User', 'Fan')

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

$user = User::create(['name' => 'Some Name', 'email' => '[email protected]']);

NeoEloquent has a fallback support for the $table variable that will be used if found and there was no $label defined on the model.

php
use NeoEloquent;

class User extends NeoEloquent {

    protected $table = 'User';

}

Do not worry about the labels formatting, You may specify them as array('Label1', 'Label2') or separate them by a column : and prepending them with a : is optional.

Soft Deleting

To enable soft deleting you'll need to use Vinelab\NeoEloquent\Eloquent\SoftDeletingTrait instead of Illuminate\Database\Eloquent\SoftDeletingTrait and just like Eloquent you'll need the $dates in your models as follows:

php
use Vinelab\NeoEloquent\Eloquent\SoftDeletingTrait;

class User extends NeoEloquent {

    use SoftDeletingTrait;

    protected $dates = ['deleted_at'];

}

Relationships

  • One-To-One
  • One-To-Many
  • Many-To-Many
  • Polymorphic

Let's go through some examples of relationships between Nodes.

One-To-One

php
class User extends NeoEloquent {

    public function phone()
    {
        return $this->hasOne('Phone');
    }

This represents an OUTGOING relationship direction from the :User node to a :Phone.

Saving
php
$phone = new Phone(['code' => 961, 'number' => '98765432'])
$relation = $user->phone()->save($phone);

The Cypher performed by this statement will be as follows:

MATCH (user:`User`)
WHERE id(user) = 1
CREATE (user)-[:PHONE]->(phone:`Phone` {code: 961, number: '98765432', created_at: 7543788, updated_at: 7543788})
RETURN phone;
Defining The Inverse Of This Relation
php
class Phone extends NeoEloquent {

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

This represents an INCOMING relationship direction from the :User node to this :Phone node.

Associating Models

Due to the fact that we do not deal with foreign keys, in our case it is much more than just setting the foreign key attribute on the parent model. In Neo4j (and Graph in general) a relationship is an entity itself that can also have attributes of its own, hence the introduction of Edges

Note: Associated models does not persist relations automatically when calling associate().

php
$account = Account::find(1986);

// $relation will be Vinelab\NeoEloquent\Eloquent\Edges\EdgeIn
$relation = $user->account()->associate($account);

// Save the relation
$relation->save();

The Cypher performed by this statement will be as follows:

MATCH (account:`Account`), (user:`User`)
WHERE id(account) = 1986 AND id(user) = 9862
MERGE (account)hasMany('Post', 'POSTED');
    }
}

This represents an OUTGOING relationship direction from the :User node to the :Post node.

php
$user = User::find(1);
$post = new Post(['title' => 'The Title', 'body' => 'Hot Body']);
$user->posts()->save($post);

Similar to One-To-One relationships the returned value from a save() statement is an Edge[In|Out]

The Cypher performed by this statement will be as follows:

MATCH (user:`User`)
WHERE id(user) = 1
CREATE (user)-[rel_user_post:POSTED]->(post:`Post` {title: 'The Title', body: 'Hot Body', created_at: '15-05-2014', updated_at: '15-05-2014'})
RETURN rel_user_post;
Defining The Inverse Of This Relation
php
class Post extends NeoEloquent {

    public function author()
    {
        return $this->belongsTo('User', 'POSTED');
    }
}

This represents an INCOMING relationship direction from the :User node to this :Post node.

Many-To-Many

php
class User extends NeoEloquent {

    public function followers()
    {
        return $this->belongsToMany('User', 'FOLLOWS');
    }
}

This represents an INCOMING relationship between a :User node and another :User.

php
$jd = User::find(1012);
$mc = User::find(1013);

$jd follows $mc:

php
$jd->followers()->save($mc);

Or using the attach() method:

php
$jd->followers()->attach($mc);
// Or..
$jd->followers()->attach(1013); // 1013 being the id of $mc ($mc->getKey())

The Cypher performed by this statement will be as follows:

MATCH (user:`User`), (followers:`User`)
WHERE id(user) = 1012 AND id(followers) = 1013
CREATE (followers)-[:FOLLOWS]->(user)
RETURN rel_follows;

$mc follows $jd back:

php
$mc->followers()->save($jd);

The Cypher performed by this statement will be as follows:

MATCH (user:`User`), (followers:`User`)
WHERE id(user) = 1013 AND id(followers) = 1012
CREATE (user)-[rel_user_followers:FOLLOWS]->(followers)
RETURN rel_follows;

get the followers of $jd

php
$followers = $jd->followers;

The Cypher performed by this statement will be as follows:

MATCH (user:`User`), (followers:`User`), (user)-[rel_user_followers:FOLLOWS]-(followers)
WHERE id(user) = 1012
RETURN rel_follows;

Dynamic Properties

php
class Phone extends NeoEloquent {

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

}

$phone = Phone::find(1006);
$user = $phone->user;
// or getting an attribute out of the related model
$name = $phone->user->name;

Polymorphic

The concept behind Polymorphic relations is purely relational to the bone but when it comes to graph we are representing it as a HyperEdge.

Hyper edges involves three models, the parent model, hyper model and related model represented in the following figure:

Similarly in code this will be represented by three models User Comment and Post where a User with id 1 posts a Post and a User with id 6 COMMENTED a Comment ON that Post as follows:

php
class User extends NeoEloquent {

    public function comments($morph = null)
    {
        return $this->hyperMorph($morph, 'Comment', 'COMMENTED', 'ON');
    }

}

In order to keep things simple but still involving the three models we will have to pass the $morph which is any commentable model, in our case it's either a Video or a Post model.

Note: Make sure to have it defaulting to null so that we can Dynamicly or Eager load with $user->comments later on.

Creating a Comment with the create() method.

php
$user = User::find(6);
$post = Post::find(2);

$user->comments($post)->create(['text' => 'Totally agree!', 'likes' => 0, 'abuse' => 0]);

As usual we will have returned an Edge, but this time it's not directed it is an instance of HyperEdge, read more about HyperEdges here.

Or you may save a Comment instance:

php
$comment = new Comment(['text' => 'Magnificent', 'likes' => 0, 'abuse' => 0]);

$user->comments($post)->save($comment);

Also all the functionalities found in a BelongsToMany relationship are supported like attaching models by Ids:

php
$user->comments($post)->attach([$id, $otherId]);

Or detaching models:

php
$user->comments($post)->detach($comment); // or $comment->id

Sync too:

php
$user->comments($post)->sync([$id, $otherId, $someId]);

Retrieving Polymorphic Relations

From our previous example we will use the Video model to retrieve their comments:

php
class Video extends NeoEloquent {

    public function comments()
    {
        return $this->morphMany('Comment', 'ON');
    }

}
Dynamicly Loading Morph Model
php
$video = Video::find(3);
$comments = $video->comments;
Eager Loading Morph Model
php
$video = Video::with('comments')->find(3);
foreach ($video->comments as $comment)
{
    //
}

Retrieving The Inverse of a Polymorphic Relation

php
class Comment extends NeoEloquent {

    public function commentable()
    {
        return $this->morphTo();
    }

}
php
$postComment = Comment::find(7);
$post = $comment->commentable;

$videoComment = Comment::find(5);
$video = $comment->commentable;

// You can also eager load them
Comment::with('commentable')->get();

You may also specify the type of morph you would like returned:

php
class Comment extends NeoEloquent {

    public function post()
    {
        return $this->morphTo('Post', 'ON');
    }

    public function video()
    {
        return $this->morphTo('Video', 'ON');
    }

}

Polymorphic Relations In Short

To drill things down here's how our three models involved in a Polymorphic relationship connect:

php
class User extends NeoEloquent {

    public function comments($morph = null)
    {
        return $this->hyperMorph($morph, 'Comment', 'COMMENTED', 'ON');
    }

}
php
class Post extends NeoEloquent { // Video is the same as this one

    public function comments()
    {
        return $this->morphMany('Comment', 'ON');
    }

}
php
class Comment extends NeoEloquent {

    public function commentable()
    {
        return $this->morphTo();
    }

}

Eager Loading

php
class Book extends NeoEloquent {

    public function author()
    {
        return $this->belongsTo('Author');
    }
}

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

PHPeloquentlaravelneo4j

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category后端框架
PricingOpen source

> Related tools

N
Node.js
基于 V8 的 JavaScript 运行时
D
Django
Python 高级 Web 框架
S
Spring Boot
Java 生态主流微服务框架