Laravel Sanitize Filename

Laravel Sanitize Filename:

In Laravel, you can sanitize filenames using the Laravel Str class which provides various string manipulation methods. To sanitize a filename, you can use the slug method to convert the filename into a URL-friendly string.

Here’s an example of sanitizing a filename using Laravel:

    
      use Illuminate\Support\Str;

      $filename = 'image with spaces.jpg';
      $sanitizedFilename = Str::slug($filename);

      echo $sanitizedFilename; // Output: image-with-spaces.jpg
    
  

In the above example, we include the Str class using the use statement to have access to the slug method. We then pass the filename 'image with spaces.jpg' to the slug method to get the sanitized version of the filename 'image-with-spaces.jpg'.

The slug method replaces any spaces or special characters in the filename with hyphens. This ensures that the filename remains safe and compatible with URLs and file systems.

You can use this sanitized filename for various purposes, such as storing uploaded files or generating download links.

Similar post

Leave a comment