database

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.

Author: Danyal
I'm a skilled programmer specializing in Vue.js/Nuxt.js for front-end development and PHP Laravel for back-end solutions. I have a strong focus on API design and development, complemented by experience in web server setup and maintenance. My versatile expertise ensures seamless creation and maintenance of web applications, covering everything from intuitive user interfaces to robust server-side functionality. Passionate about coding and driven by a lifelong learning mindset, I invite you to explore more at danyal.dk.