0

I have class to define import to news table of database from xlsx file. App\Imports\NewsImport.php

<?php
namespace App\Imports;

use App\News;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\WithHeadingRow;

class NewsImport implements ToCollection, WithHeadingRow
{
    public function collection(Collection $rows)
    {
        News::truncate();
        foreach ($rows as $row) 
        { 
            News::create([
               'title'      => $row['title'], 
               'fulltext'   => $row['fulltext'], 
            ]);
        }
      return $newsimported = $rows->count();
    }
}

then import is managed in SeedController App\Admin\Controllers\SeedController.php

<?php
namespace App\Admin\Controllers;

use App\Http\Controllers\Controller;
use Encore\Admin\Controllers\Dashboard;
use Encore\Admin\Layout\Column;
use Encore\Admin\Layout\Content;
use Encore\Admin\Layout\Row;
use App\Imports\NewsImport;
use Maatwebsite\Excel\Facades\Excel;

class SeedController extends Controller
{
    public function index(Content $content)
    {
        Excel::import(new NewsImport,       'import/news.xlsm');
        return $content
            ->title('Import & Export')
            ->description('Laravel excel');
    }

}

I launch import when I go to seed page

$router->get('seed', 'SeedController@index')->name('admin.home');

Code is working, but I want to show on seed page how many news have been imported. But I don't know how to make $newsimported available in SeedController index function. Any ideas?

1 Answer 1

1

Without looking into the implementation details of the Excel library you could try adding a member variable to that Import class you have created and then checking that after Excel::import(...) has ran:

class NewsImport implements ToCollection, WithHeadingRow
{
    public $rowCount = null;

    public function collection(Collection $rows)
    {
        News::truncate();
        foreach ($rows as $row) 
        { 
            News::create([
               'title'      => $row['title'], 
               'fulltext'   => $row['fulltext'], 
            ]);
        }

        $this->rowCount = $rows->count();
    }
}

Then where you are running Excel::import(...):

public function index(Content $content)
{
    Excel::import($import = new NewsImport, 'import/news.xlsm');

    $rowCount = $import->rowCount;

    ...    
}
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.