Get an image extension from an uploaded file in Laravel

To get the extension of an uploaded file in Laravel, you can use the getClientOriginalExtension method of the UploadedFile instance, which is available in the request object.

Here's an example of how you can use it:

use Illuminate\Http\Request;

public function store(Request $request)
    $file = $request->file('file');
    $extension = $file->getClientOriginalExtension();

    // You can now use the $extension variable to store the file, for example.

Watch a course Learn object oriented PHP

This will give you the extension of the uploaded file (e.g. 'jpg', 'png', etc.). If you want to get the original file name with the extension, you can use the getClientOriginalName method instead.

$fileName = $file->getClientOriginalName();

Note that this will only work if the file was successfully uploaded. You should also check if the file was uploaded before trying to access it, using the isValid method.

if ($request->hasFile('file') && $request->file('file')->isValid()) {
    // The file is valid and was successfully uploaded