How to upload Laravel pictures

Learn how to upload images with Laravel! Step-by-step example shows you how to store and manage images easily.

Uploading Laravel Images

Uploading images to a Laravel application is a relatively simple process. In this tutorial, we will learn how to upload images to a Laravel application. We will use Laravel's built-in file system to upload images and store them in a public folder.

First, we'll create a folder in the public directory for our images. In our example, we'll use the name "images". To do this, navigate to the public directory in your Laravel application and create a folder called "images".


// Navigate to the public directory
cd public
// Create the images folder
mkdir images

Next, we'll create a new controller to handle the image upload. To do this, we'll use the artisan command:


php artisan make:controller ImageController

This will create a new controller in the app/Http/Controllers directory. In this controller, we'll add a method to handle the image upload.


public function uploadImage(Request $request)
{
    // validate the request
    $request->validate([
        'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
    ]);
 
    // set the image name
    $imageName = time() . '.' . $request->image->extension();
 
    // move the image to the public folder
    $request->image->move(public_path('images'), $imageName);
 
    // return the path of the uploaded image
    return '/images/' . $imageName;
}

This method validates the image and sets the image name. It then moves the image to the public folder. Finally, it returns the path of the uploaded image. We can now use this method to upload images in our Laravel application.

To upload an image, we'll send a POST request to the /image endpoint, with the image as a form parameter. The response will be the URL of the uploaded image, which we can use to display the image.


// Make a POST request to the /image endpoint
fetch('/image', {
    method: 'POST',
    body: formData
})
    .then(response => response.json())
    .then(data => {
        // data will contain the URL of the uploaded image
        let imageUrl = data;
    });

We've now seen how to upload images to a Laravel application. We've created a folder in the public directory for our images, created a controller to handle the image upload, and used a POST request to upload the image. We can now use the returned URL to display the uploaded image.

Answers (0)