0

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?

6
  • Why do you want to have separate headings? Wouldn't it be easier to just comma-separate the words in one column? Commented Nov 12, 2019 at 13:40
  • Unfortunately this is the business requirement, @MatthiasS. Commented Nov 12, 2019 at 13:41
  • How are your hobbies stored currently? Commented Nov 12, 2019 at 13:41
  • They are stored in a pivot table hobby_user, which holds user_id and hobby_id. Is that of any help? Commented Nov 12, 2019 at 13:43
  • Yeah I will write down some answer for you Commented Nov 12, 2019 at 13:47

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.