Upload and Handle File and Image in Laravel

Define upload field in the form

Firstly, add an <input type="file"> field to the HTML form to allow users to select a file or image for uploading.

<form method="POST" action="{{ route('upload') }}" enctype="multipart/form-data">
    @csrf
    <input type="file" name="file">
    <button type="submit">Upload</button>
</form>

 

Handle the upload request

In a Laravel controller, you can handle the upload request in a method. Use the Illuminate\Http\Request object to access the uploaded file and perform necessary handling operations.

use Illuminate\Http\Request;

public function upload(Request $request)
{
    if ($request->hasFile('file')) {
        $file = $request->file('file');
        // Handle the file here
    }
}

 

Store the file

Laravel provides a store method to store the uploaded file. Simply call this method on the file object and provide the desired storage path.

$path = $file->store('uploads');

 

Handle the image

If you need to handle an image, such as resizing, cropping, or applying filters, you can use an image processing library like Intervention Image. First, install the Intervention Image package via Composer:

composer require intervention/image

Then, you can use the library's methods to process the image.

use Intervention\Image\Facades\Image;

public function upload(Request $request)
{
    if ($request->hasFile('file')) {
        $file = $request->file('file');
        $image = Image::make($file);
        // Handle the image here
    }
}

 

Display the uploaded file and image

Finally, you can display the uploaded file and image in the user interface. Use Laravel's helper methods to generate public URLs for the stored file and image, and use them in HTML or CSS.

$url = asset('storage/' . $path);

 

You can use the $url variable in HTML or CSS to display the uploaded file or image.

 

By following these steps and utilizing Laravel's built-in features, you can easily upload and handle files and images in your Laravel application.