DEV Community

Joël Harkes
Joël Harkes

Posted on

Fake Laravel Eloquent relations on the fly

Sometimes you just want to quickly demo something, you are not bothered by constantly setting up your data and relationships.

Its actually super easy to just fake your relationships on the Fly:

trait FakeEloquentRelationships {
    public bool $fakingRelations = false;

    protected function getRelationshipFromMethod($method)
    {
        if ($this->fakingRelations) {
            $relationShip = $this->$method();
            if ($relationShip instanceof Relation) {
                $model = $relationShip->getModel();
                $class = get_class($model);
                $factory = app(Factory::class);

                $item = $factory->of($class)
                   ->state('full') // i use state 'full' to make sure all properties are set but you can ignore this.
                   ->make();
                $expectSingle = $relationShip instanceof BelongsTo || $relationShip instanceof  HasOne;

                return $expectSingle ? $item : [$item];
            }
        }
        parent::getRelationshipFromMethod($method);
    }
}

Now you can use this trait FakeEloquentRelationships on your model set $model->fakingRelations = true and you are good to go. For example:

class User {
    use FakeEloquentRelationships;

    public function role()
    {
        return $this->belongsTo(Role::class);
    }
}


$user = app(Factory::class)->of(User::class)->make();
$user->fakingRelations = true;
$user->role; // welcome to your completely faked role :)

Hope you liked my post.

PS: we actually use this to generate our Open API (swagger) documentation in combination with league/fractal transformers.

Top comments (2)

Collapse
 
tagcoin profile image
Sandro

Nice article:) But I have a question: what's is the Factory::class that you use in your example? Which Factory::class?

Collapse
 
joelharkes profile image
Joël Harkes

Good point the app(Factory::class) is outdated you now probably want to do $class::factory() instead to get the factory of that class.