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 skilled programmer with expertise in Vue.js/Nux.js for front-end development and PHP Laravel for back-end development. I excel in building APIs and services, and also have experience in web server setup & maintenance. My versatile skill set allows you to develop and maintain web applications effectively, from the user interface to the server-side functionality. I love coding with never ending learning attitude, thanks for visiting danya.dk