Upload user avatar using laravel Livewire
Tech Stack: bootstrap-5, livewire
Demo
Code
Please login to View/Download the Code
Usage
@livewire('user-avatar')
Documentation
File uploads in Livewire are made very simple. In order to take advantage of the file uploads functionality in livewire, You need to include the following trait in your component.
use WithFileUploads;
Once you include this trait and bind your file input on the front end to a property on the backend, everything becomes smooth after that.
To store the file in your file system, you just have to use Laravel's store
function.
$this->avatar->store('/', 'public');
Since we are changing the user avatar, to test this component you must have laravel Authentication enabled on the project. You must be logged in to change the avatar of the user.
The image path of the Avatar is stored in the user's table, if your user table doesn't already have a column to store the avatar path, you can use the above-provided migration file to add a new column named avatar to the user table.
Once you have the new column migrated. Add the avatarUrl method to the User Model as shown above.
The avatarUrl method returns the URL path of the avatar image of the user if it's set if not, it returns a generic gravatar image.
Also since we are storing the images in the storage folder in order for it to be publicly accessible you must run the following command in your project root.
php artisan storage:link