I'm working with an Excel improtation function (Using maatwebsite/excel package) and I have that part covered, but I also need to have a function that'd allow apreview "sneak peek" before the file is uploaded.
I did manage to make it work (pic - https://imgur.com/rySv3Ck), but it ONLY works a certain way - code:
public function MakeImportPreview(Request $request)
{
    $dataPreview = Excel::toCollection(new ClientsImport(), $request->file('file'));
    $randomDataPreviews = $dataPreview->get(0)
        ->take(20)
        ->reject(function($row) {
            return
                !isset($row['name'])
                || !isset($row['email'])
                || is_null($row['name'])
                || is_null($row['email'])
                || empty($row['name'])
                || empty($row['email']);
        })
        ->toArray();
    return view('clients.preview', compact('randomDataPreviews'));
}
From the ClientsImportPreview class:
class ClientsImportPreview implements ToCollection, WithHeadingRow, WithLimit
{
public function collection(Collection $rows)
{
   return $rows->get(0)->reject(function($row) {
       return
           !isset($row['name'])
           || !isset($row['email'])
           || is_null($row['name'])
           || is_null($row['email'])
           || empty($row['name'])
           || empty($row['email']);
   })->take(20);
}
public function limit(): int
{
    return 20;
}
}
Basically, usage of reject and checking for emptiness/not being set was the only way I could make it work.
Is there a way to make this work by looking for the populated fields, as opposed to non-populated ones?
For example, if I try the following code instead:
public function MakeImportPreview(Request $request)
{
    $dataPreview = Excel::toCollection(new ClientsImport(), $request->file('file'));
    $randomDataPreviews = $dataPreview->get(0)
        ->take(20)
        ->map(function($row) {
            return
                isset($row['name'])
                || isset($row['email'])
                || !is_null($row['name'])
                || !is_null($row['email'])
                || !empty($row['name'])
                || !empty($row['email']);
        })
        ->toArray();
    return view('clients.preview', compact('randomDataPreviews'));
}
  class ClientsImportPreview implements ToCollection, WithHeadingRow, WithLimit
{
public function collection(Collection $rows)
{
   return $rows->get(0)->reject(function($row) {
       return
           !isset($row['name'])
           || !isset($row['email'])
           || is_null($row['name'])
           || is_null($row['email'])
           || empty($row['name'])
           || empty($row['email']);
   })->take(20);
}
I then get the following result -https://imgur.com/6iFKH4Y.
Any help is greatly appreciated. Thanks in advance!
via Chebli Mohamed
 
Aucun commentaire:
Enregistrer un commentaire