Laravel & Php

Laravel import file without Maatwebsite package


Laravel import file without Maatwebsite package

If you plan to use a form to upload and submit a CSV file, you can handle the CSV import in a controller method instead of an Artisan command. Here’s how you can set it up using a form to upload the file.

Step 1: Create a Form for CSV Upload

Create a form that allows the user to upload a CSV file. In your Blade view (resources/views/upload.blade.php), add a form:

<form action="{{ route('wp_leads.import') }}" method="POST" enctype="multipart/form-data">
    @csrf
    <div>
        <label for="csv_file">Upload CSV File</label>
        <input type="file" name="csv_file" id="csv_file" required>
    </div>
    <button type="submit">Import CSV</button>
</form>

Step 2: Create a Route

In your routes/web.php, define the route to handle the CSV file upload:

use App\Http\Controllers\WpLeadsController;

Route::post('/wp-leads/import', [WpLeadsController::class, 'import'])->name('wp_leads.import');

Step 3: Create the Controller

Generate the controller to handle the file processing:

php artisan make:controller WpLeadsController

In the newly created controller (app/Http/Controllers/WpLeadsController.php), add the logic to process the CSV:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;

class WpLeadsController extends Controller
{
    public function import(Request $request)
    {
        // Validate the file upload
        $validator = Validator::make($request->all(), [
            'csv_file' => 'required|mimes:csv,txt|max:2048', // validate file type and size
        ]);

        if ($validator->fails()) {
            return redirect()->back()->withErrors($validator)->withInput();
        }

        $file = $request->file('csv_file');
        $filePath = $file->getRealPath(); // Get the real path of the file

        // Open and read the CSV file
        if (($handle = fopen($filePath, 'r')) !== false) {
            $header = fgetcsv($handle); // Get the CSV header

            while (($row = fgetcsv($handle, 1000, ',')) !== false) {
                $data = array_combine($header, $row); // Combine header with row data

                // Insert each row into the wp_leads table
                DB::table('wp_leads')->insert([
                    'id' => $data['id'],
                    'code' => $data['code'],
                    'first_name' => $data['first_name'],
                    'last_name' => $data['last_name'],
                    'email' => $data['email'],
                    'phone_number' => $data['phone_number'],
                    'whatsapp_phone_number' => $data['whatsapp_phone_number'],
                    'country' => $data['country'],
                    'facebook' => $data['facebook'],
                    'twitter' => $data['twitter'],
                    'instagram' => $data['instagram'],
                    'website' => $data['website'],
                    'type' => $data['type'],
                    'business_type' => $data['business_type'],
                ]);
            }

            fclose($handle);
        }

        return redirect()->back()->with('success', 'CSV imported successfully.');
    }
}

Step 4: Create Success and Error Feedback

In your Blade view, display success and error messages:

@if(session('success'))
    <div>{{ session('success') }}</div>
@endif

@if($errors->any())
    <div>
        <ul>
            @foreach ($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
    </div>
@endif

Step 5: Handling File Upload and Storage

The import() method:

  • Validates the uploaded file to ensure it’s a CSV.
  • Processes the file by reading the contents, combining the headers with row data, and inserting into the database.

Step 6: CSRF and File Size Considerations

Ensure that you have file size limits configured in php.ini (if needed):

upload_max_filesize = 5M
post_max_size = 5M

Also, make sure you have CSRF protection enabled (@csrf) in your forms.

This approach will allow you to handle CSV uploads via a form, making it suitable for web-based interaction.

Let me know if you need any tweaks!


Laravel Mysql PHP
Share with Friends

Like this chef? Share with friends..