How to upload an image in laravel?

by cortez.connelly , in category: PHP Frameworks , a year ago

How to upload an image in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by dedrick , a year ago

@cortez.connelly 

To upload an image in Laravel, you can follow these steps:

  1. Make sure that you have configured your environment correctly, including your database settings and storage configurations.
  2. 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>


  1. 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');


  1. 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.';
    }
}


  1. Finally, make sure that the images directory exists in your public folder. If not, create it by running the following command:
1
mkdir public/images


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.

Related Threads:

How to preview image before upload in Laravel?
How to upload image with ajax in laravel?
How to resize image before upload in Laravel?
How to image upload into database using laravel?
How to reduce size of image in laravel when upload?
How to upload image to server using php laravel?