Laravel

How to Create File Object from Path in Laravel?

In this tutorial, we will show you how to create file objects in laravel. you’ll learn laravel to create file objects from the path. we will help you to give an example of how to create an image object from the path in laravel. I’m going to show you about laravel creating image objects from the path.

Follow below tutorial example to create file objects from URLs in laravel 6, laravel 7 and laravel 8.

Whenever you need to create a file object from the absolute path in laravel then this post will help you to create an image object from URL in laravel. sometimes we need to store images into folders using storage then you need to create file objects from the path. Then that object can be used.

So let’s see below controller code and output as below:

Controller Code:

<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\File\UploadedFile;
  
class FileController extends Controller
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    public function create()
    {
        $fileObject = $this->createFileObject(public_path('datatable-angular.png'));
  
        dd($fileObject);           
    }
  
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    public function createFileObject($url){
  
        $path_parts = pathinfo($url);
  
        $newPath = $path_parts['dirname'] . '/tmp-files/';
        if(!is_dir ($newPath)){
            mkdir($newPath, 0777);
        }
  
        $newUrl = $newPath . $path_parts['basename'];
        copy($url, $newUrl);
        $imgInfo = getimagesize($newUrl);
  
        $file = new UploadedFile(
            $newUrl,
            $path_parts['basename'],
            $imgInfo['mime'],
            filesize($url),
            true,
            TRUE
        );
  
        return $file;
    }
}

Output:

Shaiv Roy

Hy Myself shaiv roy, I am a passionate blogger and love to share ideas among people, I am having good experience with laravel, vue js, react, flutter and doing website and app development work from last 7 years.

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button