Laravel 5.4 #16 : Add profile avatar to users

That users can add their profile photo is a functionality that any web has. That’s why we are going to add it to our project.

First of all, we are going to generate a migration, since we have to add a new field to the database. To generate a migration you can look how it is done in other posts of mine. The content that our new migration will have will be:

If you look, it has a default value, so we have to put the name of the image that we want it to show by default and this image should be in public/uploads/avatars . Execute the migration.

 

Now, we are going to add the routes:

The first route will be the one that shows the profile of the user and the second will be the one that will allow us to edit it.

 

Create the controller  UserController.php :

Profile method send the logged user’s data to the view.

Update_profile method validate that what we send is an image, upload it to de directory  public/uploads/avatars  and later save the name in the database and redirect to the profile.

The profile view contains the image and user name and a form to change the profile avatar:

 

And finally, we add in the header the image and in the dropdown a link to the profile of the logged user:

 

This post was mostly to see how to upload files with Laravel to our server and we have already seen that it is very simple. This can also be applied to other types of files, but, of course, with different validations.

You could also add more fields (not just the avatar) to modify and improve the structure, putting the form on another separate page or a modal window. This, maybe, I will do it in another post later.

-

– https://devdojo.com/episode/laravel-user-image

– http://laravel-tricks.com/tricks/laravel-54-upload-image-with-validation-example