Sharim's avatar

Passing variable to the construct from controller

I want to export Products by tag. when I do dd($products). Its giving me correct array. But the downloaded file is empty.

My controller:

public function export(Request $request) {
        
        $tag = Tag::where('id', $request->selectTag)->get()->first();
        
        $products = new ProductsExport([
            [1, 2, 3],
            [4, 5, 6]
        ]);
        $products = $tag->products()->get();
        //dd($products);

        return Excel::download($products, 'products.xlsx');
    }

ProductsExport.php

protected $products;

    public function __construct(array $products)
    {
        $this->products = $products;
    }
    public function array(): array
    {
        return $this->products;
    }

    /**
    * @return \Illuminate\Support\Collection
    */
    public function collection()
    {
        $products = Product::select(
            'name', 'code', 'price', 'slug', 'details', 'ecommerce', 'quantity',
            'description', 'created_at', 'category_id', 'origin', 'warranty')->get();
        // $category = $products->tags;
        return $products;
    }
0 likes
8 replies
Nakov's avatar
Nakov
Best Answer
Level 73

You are doing many things, and all are named the same..

try this:

return Excel::download(new ProductsExport([
            [1, 2, 3],
            [4, 5, 6]
        ]), 'products.xlsx');
Sharim's avatar

@Nakov I tried like this,

$products = $tag->products()->get();
 return Excel::download(new ProductsExport($products), 'products.xlsx');

but downloaded file has all the products instead of related with the tags.

Nakov's avatar

@Sharim but that's because you are overriding it here:

public function collection()
    {
        $products = Product::select(
            'name', 'code', 'price', 'slug', 'details', 'ecommerce', 'quantity',
            'description', 'created_at', 'category_id', 'origin', 'warranty')->get();
        // $category = $products->tags;
        return $products;
    }

it should be:

public function collection()
    {
        
        return $this->products;
    }
Sharim's avatar

@Nakov here I want to mention the specific fields only. If I do return $this->products;, it will fetch all the fields from database. How can we specify it?

Nakov's avatar

@Sharim You can use the only helper from the collection https://laravel.com/docs/9.x/collections

return $this->products->only(    'name', 'code', 'price', 'slug', 'details', 'ecommerce', 'quantity',
            'description', 'created_at', 'category_id', 'origin', 'warranty')->all();
Sharim's avatar

@Nakov I'm getting this error with only()->all()

Call to a member function all() on array

If I remove the all(), the file is empty.

Please or to participate in this conversation.