DEV Community

loading...

Fake Laravel Eloquent relations on the fly

joelharkes profile image Joël Harkes ・1 min read

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.

Discussion

pic
Editor guide