Support the ongoing development of Laravel.io →
Database Eloquent Architecture

I have two eloquent model: Foo and Bar.

class Foo extends \Eloquent {
    public function bar()
    {
        return $this->hasMany('Bar');
    }
}

class Bar extends \Eloquent {
    public function foo()
    {
        return $this->belongsTo('Foo');
    }
}

Also have two repository for the models and a base repository with metods like getAll,find,etc.

class FooRepository extends BaseRepository {

    public function __construct(Foo $model)
    {
        parent::__construct($model);
    }

    public function methodInFooRepo($fooId)
    {
        // returns an image url based on Foo's fields. Something like urlRoot . field1 . '_' . field2 . '.jpg';
    }

    public function anotherMethodInFooRepo($fooId)
    {
        // returns an url string points to Foo's detail page. A reverse routing with parameters from Foo's fields
    }
}
class BarRepository extends BaseRepository {

    public function __construct(Bar $model)
    {
        parent::__construct($model);
    }
}

I need to list all Foo with Bars, so in the Foo repository I have something like this:

return $this->model->with('Bar')->get();

Then I pass this to the view in the controller.

At the view I use a foreach like this:

foreach ($fooElements as $oneFooElement)
{
    $oneFooElement->field_in_foo;
    $oneFooElement->bar->field_in_bar;
}

Everything is working, but how can I access the methodInFooRepo() method from the view or in the controller?

Last updated 2 years ago.
0

When your controller interacts with your FooRepository and your FooRepository executes and returns:

$this->model->with('Bar')->get()

you're given Foo models with the related Bar models eager loaded. At this point, you're done with the FooRepository (it's job is done) and are working directly with those 2 models.

I'm not sure what capabilities methodInFooRepo() is supposed to provide, but it sounds like that method should probably be in Foo and not FooRepository. If your view or controller needs to continue to use FooRepository, your controller should already have a reference to that (using the IoC container or through some other way you've instantiated and made that available).

Last updated 2 years ago.
0

I'm not sure what capabilities methodInFooRepo() is supposed to provide, but it sounds like that method should probably be in Foo and not FooRepository.

Edited the original post with comments at the methods. Do you think this method must be in the Foo model? But i want a clean model file ( only with relations, id name, etc )

Last updated 2 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

moonshades moonshades Joined 16 Mar 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.