How to get file object in laravel?

by mallory_cormier , in category: PHP Frameworks , 21 days ago

How to get file object in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by aniya.jaskolski , 20 days ago

@mallory_cormier 

In Laravel, you can get a file object by using the IlluminateHttpRequest class. Here's an example of how to get a file object in a controller method:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
use IlluminateHttpRequest;

public function uploadFile(Request $request)
{
    if ($request->hasFile('file')) {
        $file = $request->file('file');

        // You can now work with the file object, such as storing it or getting its properties
        $filename = $file->getClientOriginalName();
        $filesize = $file->getSize();

        return 'File uploaded: ' . $filename;
    }

    return 'No file uploaded';
}


In this example, we first check if a file was uploaded with the hasFile method. If a file was uploaded, we retrieve the file object using the file method and then we can work with the file object as needed.