laravel-5file-uploadpostman

Method file returnsMethod Illuminate\Http\Response::file does not exist


I am trying to send a file with my API response to postman

return response($company)->file($company->logo, $company->main_photo);

laravel woops returns:

Method Illuminate\Http\Response::file does not exist.

What am I doing wrong?


Solution

  • I think you do not need to retrieve a file using the response helper method.

    it just needs to send file location to the front-end, e.g. let assume your $company object shape is something like:

    {
        id: 1234,
        name: 'My Company',
        logo: 'images/companies/logo/1425.jpg'
    }
    

    then it is enough to pass above object to your front-end and in a contract ask your front end to put http://example.com/files/ at the beginning of file address then or you may define a JsonResource class and override the logo path with the absolute address (append base-URL to the beginning).

    it might look like:

    <?php
    
    namespace App\Http\Resources;
    
    use Illuminate\Http\Resources\Json\JsonResource;
    
    class ComapnyResource extends JsonResource
    {
        /**
         * Transform the resource into an array.
         *
         * @param  \Illuminate\Http\Request
         * @return array
         */
        public function toArray($request)
        {
            return [
                    'id' => $this->id,
                    'name' => $this->name,
                    'logo' => 'https://example.com/file/' . $this->logo,
            ];
        }
    }
    

    Take a look the documentation.