Search code examples
phplaravellaravel-7

How to Check file exists in Laravel


I have a Laravel Controller Function file_fetch()

public function file_fetch(Request $request) {

        $file = request('routename');
        $destinationPath = public_path('/folder/'.$file);
        
        if(!File::exists($destinationPath)){
            $content = File::get($destinationPath);
            return view('filefetch', compact('file','content'));
        } 
        else {
            return redirect('/')->witherrormessage('NO such File Exists');
        }
    }

This works if i check for file public/folder/app/index.html and if i check for public/newfolder (newfolder doesnt exist) and hence it executes else function and redirects with error message, but if i search for public/folder/app/ I havent specified the file name, but the directory exists, hence the if(!File::exists($destinationPath)) function is getting executed!

i want to check just and files inside the directory and even if the directory exists, if file is not present, throw a error message, saying file doesnt exists.


Solution

  • add one more additional condition to check given path is file but not a directory

    public function file_fetch(Request $request) {
    
            $file = request('routename');
            $destinationPath = public_path('/folder/'.$file);
            
            if(!File::exists($destinationPath) && !is_dir($destinationPath)){
                $content = File::get($destinationPath);
                return view('filefetch', compact('file','content'));
            } 
            else {
                return redirect('/')->witherrormessage('NO such File Exists');
            }
        }