DEV Community

Muhamad Sulaiman
Muhamad Sulaiman

Posted on

How to enable user to upload profile photo in Laravel 8

Today I was assigned to develop a user profile function in our client web apps.

Ok, easy enough. I just need a form that has enctype and file upload.

So I thought it only needs to upload the image, then store it in DB and then show it to the front-end.

However, the flow that I thought is wrong. The flow should be very seamless. Which is when the user success registers, they can see the default profile image (set by the system, like example image). Then when users click on the image, their windows appear, choose the image and then save.


The save button should not like the default file upload (refer to Bootstrap File Input).

Also, after the user click Save Photo, the system will behave like SPA. Without refreshing the browser.

That time I know I was in trouble. Because I don't like much play around with JavaScript. I know I can achieve that using vanilla or JS Framework such as Inertia or Vue. I'm using Laravel by the way.

So after searching, I decide to use Laravel Livewire. Why?

This is mainly because I think I can make it using Livewire and not others. And the best part of Livewire is that even though I code dynamic function for Front-end, but I'm coding it using PHP Laravel. I don't know if this makes any sense to you.

So how do I develop it using Livewire?

First, after I create the component, I create a method named avatar() on User Class.


Second, in the livewire component, I use the file upload trait (because Livewire does not support file upload by default).


Then I create a method to save the avatar when the user uploaded it. Don't forget to set the avatar null to remove the button right after user successfully upload the image.


Third, in my rendering component file, I show the default image first. Then after the user saves, the image will change into a new image.


That's it. With all of these steps, you now will have a User profile functionality.

I've complete the task. Now your turn to do it better than me. Share your experience in the comment section ;)

Top comments (0)