How to Check if Request Has File or Image in Laravel?

Last updated on March 14, 2023

The hasFile() method from the Request class checks if the incoming request has a file or not. It takes the input field name as an argument and returns true when it finds the file in the incoming request.

Syntax

hasFile(string $inputFieldName)

Parameters

It has one required parameter in which you need to pass the input field name or name of the request.

Return Value

It returns bool (true or false).

Usage

You can use hasFile() method in the if-statement.

if($request->hasFile('image_input')) {
    // This code block will run when the request has the file.
}

In the above statement, we added the hasFile() method that checks if the incoming request has a file. Below is the complete code from the FileUploadController.

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class FileUploadController extends Controller
{
    public function upload(Request $request)
    {
        // it checks if request has file
        if($request->hasFile('image_input')) {

            // it prints the data of the image from request and stops further execution
            dd($request->image_input);
        }

        // it uploads the file
        $path = $request->file('image_input')->store('uploads');

        // redirect back with success message
        return redirect()->back()->with('message', 'Image has been successfully uploaded.');
    }
}

Conclusion

This article demonstrates how can you check if the incoming request has a file or image. Laravel provides hasFile() method that checks the file in the incoming request. It takes the input name as an argument and returns a bool.


Written by
I am a skilled full-stack developer with extensive experience in creating and deploying large and small-scale applications. My expertise spans front-end and back-end technologies, along with database management and server-side programming.

Share on:

Related Posts

Tags: Laravel,