@cortez.connelly
To upload an image in Laravel, you can follow these steps:
- Make sure that you have configured your environment correctly, including your database settings and storage configurations.
- Create a form in your view file to allow users to select and upload an image. For example, you can use the following form code:
1
2
3
4
5
|
<form action="/upload" method="POST" enctype="multipart/form-data">
@csrf
<input type="file" name="image">
<button type="submit">Upload</button>
</form>
|
- Define a route in your routes/web.php file to handle the image upload request. For example:
1
2
3
|
use AppHttpControllersImageController;
Route::post('/upload', [ImageController::class, 'upload'])->name('upload');
|
- Create a controller class to handle the image upload logic. Run the following command to create a new controller:
1
|
php artisan make:controller ImageController
|
Open app/Http/Controllers/ImageController.php
and add the upload
method:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
<?php
namespace AppHttpControllers;
use IlluminateHttpRequest;
class ImageController extends Controller
{
public function upload(Request $request)
{
$image = $request->file('image');
// Do validation for the uploaded image here
$imageName = $image->getClientOriginalName();
$image->move(public_path('images'), $imageName);
return 'Image uploaded successfully.';
}
}
|
- Finally, make sure that the images directory exists in your public folder. If not, create it by running the following command:
That's it! Now, when you submit the image upload form, Laravel will handle the request, save the uploaded file to the public/images
directory, and display a success message.