Hello Devs,

In this tutorial, we are going to learn how to create file object in laravel.

Given below is the solution for creating file object in laravel.

use Symfony\Component\HttpFoundation\File\UploadedFile;



Solution:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\File\UploadedFile;

class HomeController extends Controller
{
    public function getFile($url)
    {
        //get name file by url and save in object-file
        $path_parts = pathinfo($url);
        //get image info (mime, size in pixel, size in bits)
        $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,
        );
        return $file;
    }

    public function getFileObject()
    {
        $url = public_path('image/demo.jpg');
        $files = $this->getFile($url);
        dd($files);
    }


I hope this example helps you.