What is the difference between a model and a repository

Repository actually allows you to separate your business logic from database layer (Model).

Repository/Entity are very common practice being used in Symfony Framework.

Laravel introduces the Model classes as database layer and doesn’t come with Repository/Model structure default. But it can be implemented.

If you are curious to know how to implement Repository layer with Eloquent Models, stay with me to understand purpose & implementation of Repository.

Model vs Repository:

// Eloquent: getting all published posts via Model directly
$posts = Post::where('published', true)->get();

// Repository: 
$posts = $this->postRepository->getAll(true);

Repository:
When using repository, it will be easy to migrate from one framework to other, if you keep app business logic away from Model/Entity.
Let’s take a look at PostRepository

class PostRepository {
    protected $model;

    public function __construct(Post $model)
    {
        $this->model = $model;
    }

    public function getAll($published = false)
    {
        if ($published === true)
        {
            return $this->model->where('published', true)->get();
        }
        return $this->model->all();
    }
}

Controller:
This is how you will inject PostRepository in controller to take advantage of Repository.

class PostController extends Controller
{
    /**
     * @var PostRepository
     */
    protected $post;

    public function __construct(PostRepository $post)
    {
        $this->post = $post;
    }

    /**
     * PostController constructor.
     * Here you can see that action looks much cleaner with Repository implementation.
     * @param PostRepository $match
     */
    public function index()
    {
        return $this->postRepository->getAll(true);
    }
}

That’s it, see you in next post.

About the author

Danyal Ali Butt

I'm working as programmer since 2002. Born, grew up, studied and worked in Pakistan now Im located in Denmark since 2006.

View all posts