Here is how you can add image upload functionality to your Laravel application using the Laravel Form Components package:
1. Install the package via Composer:
bash
composer require protonemedia/laravel-form-components
2. Create a form component in your Blade template that includes a file input field:
html
<x-form action="{{ route('profile.update') }}" method="POST" enctype="multipart/form-data">
<x-form-section>
<x-slot name="title">Profile Picture</x-slot>
<x-slot name="description">Update your profile picture.</x-slot>
<x-form-row>
<x-label for="profile_picture" value="Profile Picture" />
<x-form-component>
<input type="file" name="profile_picture" id="profile_picture" />
</x-form-component>
</x-form-row>
</x-form-section>
<x-form-actions>
<x-button type="submit">Save</x-button>
</x-form-actions>
</x-form>
3. In your controller, handle the file upload:
php
public function update(Request $request)
{
$request->validate([
'profile_picture' => ['required', 'image', 'max:2048'],
]);
$path = $request->file('profile_picture')->store('profile-pictures', 'public');
auth()->user()->update([
'profile_picture' => basename($path),
]);
return redirect()->route('profile.edit')->with('success', 'Profile picture updated.');
}
4. Update your User model to include the profile picture attribute:
php
class User extends Authenticatable
{
protected $fillable = [
'name',
'email',
'profile_picture',
];
}
5. Run the migration to add the profile_picture column to the users table:
bash
php artisan migrate
6. Create a symbolic link to make the uploaded files accessible from the web:
bash
php artisan storage:link
7. Display the uploaded image in your Blade template:
html
<img src="{{ asset('storage/profile-pictures/' . auth()->user()->profile_picture) }}" alt="Profile Picture">
That's it! You now have a working image upload functionality in your Laravel application using the Laravel Form Components package. The package provides a set of Blade components that make it easy to create forms and handle file uploads.
Citations:[1] https://wpwebinfotech.com/blog/how-to-upload-image-in-laravel/
[2] https://stackoverflow.com/questions/24568200/upload-image-using-laravel-with-formmodel
[3] https://livewire.laravel.com/docs/uploads
[4] https://dev.to/vimuth7/create-a-image-upload-component-for-laravel-breeze-inertia-and-vue-3-o0i
[5] https://github.com/protonemedia/laravel-form-components/issues/90