Having difficulty handling file data following the import of an Excel file in Laravel 5.8

I have a requirement to send multiple emails at once by importing an Excel file. Currently, I am successfully importing the Excel file and storing the data in a variable as an array. I am utilizing maatwebsite/excel version 3.1 for this task. However, after importing the file, the data is being stored in the variable as a nested array with null values in the remaining columns of the Excel file. I attempted to use array_filter but encountered issues. You can view the current response screenshot here - response in console .

Within EmailsController:

public function sendEmailUsingFileAndSave(Request $request)
{
    //variables like $content, $fromemail, $fromname are defined here

    $file = $request->file('file');

    $import = new EmailsImport;
    Excel::import($import, $file);
    return $emails = $import->data;
    foreach($emails as $email)
    {
        Mail::send('email.content', ['content' => $content], function($message)
             use ($email, $subject, $fromemail, $fromname) {
                  $message->to($email)->subject($subject);
                  $message->from($fromemail, $fromname);
             });
     }
}

Located in app\imports folder, EmailsImport.php contains:

<?php

namespace App\Imports;

use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\Importable;
use Maatwebsite\Excel\Concerns\WithValidation;

class EmailsImport implements ToCollection, WithValidation 
{
    use Importable;

    public $data;

    public function collection(Collection $rows)
    {
        $this->data = $rows;
    }
 }

The expected response should be:

(2) ["<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7312111033160b121e031f165d101c1e">[email protected]</a>","<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="93ebeae9d3f6ebf2fee3fff6bdf0fcfe">[email protected]</a>", "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a2c3c0c1e2c3cccdd6cac7d08cc1cdcf">[email protected]</a>"]

You can download a sample Excel file here - sample excel file

I have been facing challenges with this process for some time now. Would appreciate any assistance in resolving this issue.

Answer №1

Is the issue you're facing related to filtering?

If so, you can resolve it by incorporating the code snippet below:

Excel::import($import, $file);

$emails = [];
foreach ($import->data as $item) {
  $item = array_filter($item, function($value) { return !is_null($value) && $value !== ''; });
  foreach ($item as $i) {
    $emails[] = $i;
  }
}

foreach($emails as $email)

Answer №2

The issue you're facing is that the Maatwebsite\Excel library interprets some empty cells in your excel sheet as part of the row. This results in a two-dimensional array being assigned to $this->data when using the ToCollection interface.

To resolve this, one approach is to iterate through each row in the $rows collection with a foreach loop and only add the first cell of each row to $this-data. You can achieve this by implementing something similar to the following code:

class EmailsImport implements ToCollection, WithValidation 
{
    use Importable;

    public $data = [];

    public function collection(Collection $rows)
    {
        foreach ($rows as $row) {
            $this->data[] = $row[0];
        }
    }
 }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ways to combine multiple arrays

Here are two arrays: Array1 ( [0] => 1 [1] => 2 [2] => 3 ) Array2 ( [0] => a [1] => b [2] => c ) I would like to create Array3 where: Array3 Like ( [0] => ([0]=>1 [1]=>a) [1] => ([0]=>2 [1 ...

Get a glimpse of only the photos stored within a designated directory using PHP

I'm attempting to display only image files from a specific folder using PHP and have tried the following code: $dirname = "users/".trim($_GET['nome']); $files = array(); if (is_dir($dirname)) {} else {mkdir($dirname, 0777);} $di ...

"I am trying to figure out how to set a link to an image using JavaScript. Can someone help me

I need help figuring out how to insert an image or gif file within two inverted commas '' in this line of code: _("status").innerHTML = ''; (line number 13 in the actual code) Your assistance with this question would be greatly appreci ...

What is the alternative for mysql_fetch_length function in CodeIgniter?

I need to calculate the total number of characters returned by a database query. In my PHP code, I'm currently utilizing mysql_fetch_length. Does CodeIgniter have a comparable function for this purpose? ...

Having trouble sending the checkbox value using AJAX

I retrieved a table from the database: <p id="result"></p> <?php //$id = $_SESSION['staff_id']; $teamResult = getQuarter($leader_id); $count1 = 0; if (mysqli_num_rows($teamResult) > 0) { ?> <table id="confirm"& ...

How to send an email with an attachment using jQuery AJAX and PHP

I have developed a program for sending emails with attachments. Initially, I created it without using ajax and it worked perfectly fine. However, when I tried implementing jQuery ajax, the functionality stopped working. Upon clicking the apply button, noth ...

Having trouble with your PHP conditional statements? The IF, ELSEIF, and ELSE might

I've encountered an issue with my PHP script that is designed to update a flat file based on variables passed from an HTML form. The problem lies in the if / elseif / else statement, as it fails to open the correct file during comparison. No matter wh ...

What could be causing the TypeError I encounter when trying to import @wordpress/element?

Encountering a similar issue as discussed in this related question. This time, I've switched to using '@wordpress/element' instead of 'react-dom/client' based on the recommendation that it also leverages React functionalities. Ho ...

Accessing the Key Name of a JSON Array in Android Using Dynamic Methods

I have a unique json url, which upon opening displays the following data { "Response": "Successful", "All_Items": [{ "Category": "1", "TotalCount": "5", "ExpiringToday": 2 }], "TopOne": [{ "id": "10", "ThumbnailPath": "http://exampleo ...

What steps can be taken to prevent the execution of any file within a designated Apache directory?

My setup involves using apache2 and php. I have created a form that allows users to upload files to a specific directory. While I have implemented various security measures, I am keen on preventing the execution of any file within that directory. The inten ...

Which is the better option: utilizing the submit event of the form, or incorporating ajax functionality?

Forms are an essential part of my website design, and I often find myself contemplating whether it's better to submit a form using a standard submit button or utilizing Ajax. Typically, I opt for Ajax to prevent the dreaded issue of form re-submission ...

Sending Data from PHP Controller to Ajax

I have implemented a Model-View-Controller (MVC) architecture for my website. In this setup, I have a button that triggers an AJAX call to remove an uploaded image from the site. Here is an excerpt from my Model: public function remove_document($document ...

Display and pass a dynamic array within a Tectite format email template

For my project, I am utilizing Tectite Form mail to send emails. The templates being utilized are named as example1.email.html files. I am looking for a way to pass a dynamic array in the mail options from the PHP script to this template and then extract ...

The table element fails to display in IE11 due to a rendering issue, displaying the error message: "Render error - TypeError: Object does not support the property or method 'entries'"

As someone new to web app development, I am currently working on a project that involves using Vue cli and antd components, with the additional challenge of ensuring compatibility with IE11. However, I have encountered an issue where IE11 does not render ...

What is the best way to implement an automatic logout feature in PHP?

I develop websites with login/logout functionality. Whenever a link or button is clicked on the website, I use an ajax function to verify the user's login status and automatically log them out if their session has expired. The logout function also up ...

Integrate AngularJS with Laravel for efficient routing management

In my current web app project, I am utilizing AngularJS and Laravel for the development. Below is a breakdown of how my routing is set up: AngularJS: angular.config(['$stateProvider','$urlRouterProvider',function($stateProvider,$urlRo ...

Switch Between Different Components in VueJS

I am currently working on a VueJS project to create a navigation bar with toggleable drop-down menus. While I can successfully toggle individual menus, I am struggling to figure out how to handle multiple drop-down menus so that when one menu is opened, th ...

"Implementing Vue mousemove functionality only when the mouse button is pressed

Is it possible to initiate a mouse movement only after the element has been clicked first? I am exploring this functionality for an audio player timeline. .player__time--bar(@mousedown="setNewCurrentPosition($event)") .slider(role="slider" aria-valuem ...

Nuxt.js static pages with relative URLs

I am currently working on developing static pages with Nuxt.js (MPA). After executing the generate command, I noticed that all the URLs in the <nuxt-link> tag start from the root directory, specifically /. For instance, my project structure looks lik ...

Transmit an echo using AJAX

Apologies if this question has already been asked, I tried searching but couldn't find any answers (OR didn't understand the answer). I have a hyperlink and would like to retrieve the value using AJAX. Here is an example with PHP: HOME <a h ...