How To Check If Request Has A File In Laravel?

Hello artisan,

In this tutorial, I will show you if the request has file in laravel. From this tutorial, you will learn laravel check request has file. If you have any question about laravel check if request is file then I will give a complete solution. Laravel provides hasFile helper to check whether a file exists or not in a request.

We can use this code with laravel 6, laravel 7, laravel 8 and laravel 9 versions. It is a good practice to check request input file object is empty or not in laravel before saving data. We can use hasFile() method of request object. we can check request has file or not in laravel controller also. so let's see the simple example code.

namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
  
class PostController extends Controller
{
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index(Request $request)
    {
        $request->validate([
            'name' => 'required',
            'photo' => 'required',
        ]);
 
        if ($request->hasFile('photo')) {
            dd($request->photo);
        }
    }
}

 

Read also: How to Check if Array Key Exists in Laravel Blade

 

Hope it can help you.

 

#laravel #validation