Search code examples
laravellaravel-5laravel-excel

Laravel Excel: Export variant headers


I am facing the following challenge with Laravel Excel, which I consider to be the best spreadsheet out there.

So, let's each row is a user and would like to generate the headings for their hobbies as such:

name, hobby_1, hobby_2, hobby_3 Jim Smith, basketball, rowing, chess, programming

Issue is, how can I produce the headings as above provided that hobbies number may vary from user to user - that is, user John Majer may have only hobby_1 => skateboard.

For now I am just printing the headings as follows:

 public function headings(): array
    {
        return [
            ...
     ];
}

Any suggestions?


Solution

  • I think from a technical point of view, the several headers are not a good requirement, as it will make it difficult to further work with the data in an automated fashion, but that might just be my opinion. But since you have to do it, my solution would be the following.

    Get the maximum amount of hobbies one user has. An example query could look like this:

    public function headings(): array
        {
            $headers = [
                // all headers before hobbies
            ];
            $result = DB::table('hobby_user')->selectRaw('user_id, count(hobby_id) as total')->groupBy('user_id')->orderBy('total', 'desc')->limit(1)->first();
            $totalHobbies = $result['total'];
            // save total hobbies somewhere in class or whereever so you can use it later to build the right amount of columns for each user
            for ($i = 1; $i <= $totalHobbies; $i++) {
                $headers[] = 'hobby_' . $i;
            }
            // now all headers after hobbies
            $headers[] = '';
            return $headers;
    }
    
    

    When you create the user entries, make sure you have the amount of hobbies available somewhere in the class or whatever, so you don't need to do the same query to fetch the total amount of hobbies each time you export a user entry.