Symfony 4 upload images using EasyAdmin

Hassan Juniedi
3 min readApr 17, 2019

If you are working on Symfony 4 project and using EasyAdmin as a backend dashboard you may have noticed that uploading images and files is not supported out of the box and that can be annoying to a lot of developers including me. So in this quick tutorial I will demonstrate how to upload images easily . In this tutorial I assume that you have a working Symfony project with EasyAdmin installed.

Setup Entity

lets assume you are working on article entity and you want to upload featured image .

class Article
{
/**
*
@ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*
@ORM\Column(type="integer")
*/
private $id;
/**
*
@ORM\Column(type="string")
*/
private $title;
/**
*
@ORM\Column(type="text")
*/
private $body;
/**
*
@ORM\Column(type="string")
*/
private $image;
}

The type of image property will be string as we are going to store the path of image on the server not the image it self in DB.

Setup EasyAdmin

Open the config file for easy admin and update Article entity as the following. in this config we tell easy admin to treat $image field as a file.

#config/packages/easy_admin.yamleasy_admin:
entities:
Article:
class: App\Entity\Article
new:
fields:
- 'title'
- 'body'
- {property: 'image', type: 'file'}

After we update the config our article form will be look something like the photo below.

Create Upload Service

Next we will create a service to save images on the server with one function called saveToDisk(UploadedFile $image) that takes one argument of type UploadedFile. When we will call this function it will save the uploaded file to the root of Symfony project in uploads/images/{year}/{month}/{day} and will return the path of saved image .e.g: uploads/images/2019/04/17/2fc2e83775ae.jpeg

Note: you will have to validate the file before saving to the disk.

use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\HttpKernel\KernelInterface;

class ImagesService
{
private $kernel;
public function __construct(KernelInterface $kernel)
{
$this->kernel = $kernel;
}

function saveToDisk(UploadedFile $image) {
$uploadDirectory = 'uploads/images/'.date("Y/m/d");
$path = $this->kernel->getProjectDir().'/public/' . $uploadDirectory;
$imageName = uniqid() . '.' . $image->guessExtension();
$image->move($path, $imageName);
return '/'. $uploadDirectory. '/' . $imageName;
}
}

Create Event Subscriber

Now we have to subscribe to pre_persist event of EasyAdmin to save the uploaded file and assign the path of saved image to $image property of Article entity.

namespace App\Subscriber;

use App\Entity\Article;
use App\Service\ImagesService;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\EventDispatcher\GenericEvent;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\HttpFoundation\Request;

class PostImageSubscriber implements EventSubscriberInterface
{
private $imagesService;

public function __construct(ImagesService $imagesService)
{
$this->imagesService = $imagesService;
}

public static function getSubscribedEvents()
{
return array(
'easy_admin.pre_persist' => array('postImage'),
);
}

function postImage(GenericEvent $event) {
$result = $event->getSubject();
$method = $event->getArgument('request')->getMethod();

if (! $result instanceof Article || $method !== Request::METHOD_POST) {
return;
}

if ($result->getImage() instanceof UploadedFile) {
$url = $this->imagesService->saveToDisk($result->getImage());
$result->setImage($url);
}
}
}

That’s it now when ever we create an article the image will be saved to the server and the path of saved image will be stored in article $image property.

If you liked this article please follow me to stay updated and clap if it was helpful to you. Thanks for reading.

--

--

Hassan Juniedi

I am a highly motivated software engineer with a passion for web development I have a keen interest in technology and problem solving .