DEV Community

Cover image for Use Hydrator in Laravel Doctrine
Reza Rabbani
Reza Rabbani

Posted on

Use Hydrator in Laravel Doctrine

Have you ever used Doctrine in Laravel? If so, this should be familier to you.

/** @ORM\Entity **/
class Book {

    /** @ORM\Column(type="string") **/
    protected $title;

    public function getTitle() {
        return $this->title;
    }

    public function setTitle($title) {
        $this->title = $title;
    }
}
Enter fullscreen mode Exit fullscreen mode

Just imagine an entity with more properties and in order of that, more setter methods. calling all of them one by one to store a new entity would be a headache.
Wouldn't it be nice if there was something that would handle it based on the keys of the data array that you have? The good news is that it's already done! but there is a lack of documentation in for using it in Laravel.

Install Requirements

First of all you should install doctrine in your laravel project. It's well explained here. Then install doctrine hydrator

composer require doctrine/doctrine-laminas-hydrator
Enter fullscreen mode Exit fullscreen mode

if you want to read more about it, checkout the documentation

Configure Hydrator

Add doctrine config file to configs directory if you haven't already

php artisan vendor:publish --tag="config"
Enter fullscreen mode Exit fullscreen mode

In config\doctrine.php register hydrator inside custom_hydration_modes key

'custom_hydration_modes'     => [
    'default' => \Doctrine\Laminas\Hydrator\DoctrineObject::class,
],
Enter fullscreen mode Exit fullscreen mode

How to use it

Now imagine a BookController

class BookController {

    protected $em;

    public function __constructor(EntityManagerInterface $em) 
    {
        $this->em = $em;
    }

    public function store(Request $request) {
        // It will find the proper setter method based on the key and passes the value to that
        $book = $this->em->newHydrator('default')->hydrate($request->all(), new Book);
        $this->em->persist($book);
        $this->em->flush();

        // whatever ...
    }
}
Enter fullscreen mode Exit fullscreen mode

That's it!
It's much cleaner than calling setter methods one by one and calling new setter methods after adding new columns to our entities.

Top comments (0)