coolpraz's avatar

Validation rule of edit file upload in storage

I have font database table where i store information about fonts and in controller i validate it before store to database like mime type, title. However, when i want to update the information about font how to validate it. Below is the list i want to validate on update on validation

  1. If file exists on storage
  2. If new file uploaded by form check its mimes type
  3. Don't required in validation rule if its already exists in storage and database column 'path'
0 likes
3 replies
sunergetic's avatar

It would help if you show us the code you have now, but with no input, this is an idea i came up with. Not necessarily a clean way of doing it (that's up to you ;) ), but one method that will always work is manual validation. Here some psuedo code:

// 

<?php

namespace App\Http\Controllers;

use Validator;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

SomeController extends Controller {
    
    public function someAction(Request $request){

        // Validate if we have a file

        $this->validate(['font' => 'file']);

        // Get the file
        $font = $request->file('font');
        $fontFilename = $font->getClientOriginalName();

        // 1) Check if exists in storage
        // Assuming the filename is not altered when uploaded



        // .. Do database validation here, and return some boolean
        $existsInDatabase = true;

        $existsInStorage = file_exists( base_path().'/path/to/'.$fontFilename); 
        
        if( ! ($existsInDatabase && $existsInStorage) ){

            // 2) If new file uploaded by form check its mimes type
            $this->validate(['font' => 'mimes:tff,woff');
        }


        


    
    }

}

Edit: removed some mistakes

timacdonald's avatar

I'd say validation should only check that its a file and its mime type is correct.

That means it is 'valid' and has passed validation.

Then i'd split out the functionality to check if its able to be stored, i.e. does the font exist already etc. I think your trying to shove a square peg into a round hole. Just let validation make sure its valid and then simply write some standard code to check if it exists.

That's my two cents.

Please or to participate in this conversation.