Laravel 11 Apexcharts Example Tutorial

             A vCard file, also known as a VCF (Virtual Contact File), is a standard format for sharing contact information. vCards can include: personal information, phone numbers, email addresses, and employment information.

Laravel 11 vCard: How to Create a vCard File in Laravel 11

Table Of Content

1 Prerequisites

1.) PHP version of >= 8.2
2.) Composer
3.) Mysql

2 Introduction

Inside this article, we will see how to Export vCard File. So let's follow the below steps and create vcard file in Laravel 11 apps.

3 Create / Install a Laravel Project

3.1 Install Laravel Project

First, ensure Composer is installed on your system. Use the following command to install a new Laravel Project:

composer create-project laravel/laravel laravel11-vcard-app

Navigate to your project directory:

cd laravel11-vcard-app

3.2 Configure MySql Database

Open the .env file and input the necessary database credentials:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=vcard
DB_USERNAME=root
DB_PASSWORD=

4 Create Migration

Next, create a migration for the posts table using the Laravel artisan command:

    php artisan make:migration create_contacts_table

In the migration file located at database/migrations, add the following code to define the contacts table structure:
    
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('contact', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email');
            $table->string('phone');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('contact');
    }
};


Run the migration:

php artisan migrate

5 Create Model

Now, create the Contact model for the posts table. Create the file at app/Models/Contact.php and add the following code:
    
<?php
namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Contact extends Model
{
    protected $fillable = [
        'name',
        'email',
        'phone',
    ];
}


6 Create Controller (ContactController)

Create a controller to handle the data loading functionality:

php artisan make:controller ContactController

In ContactController.php, create an index and exportvcard function to create vCard:

<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Contact;
use DataTables;



class ContactController extends Controller
{
    public function index(Request $request)
    {
       
        $contacts = Contact::get();
        return view('contact',compact('contacts'));
    }
    
    public function exportvcard(Request $request)
    {
       $id=$request->id;
        $user=Contact::find($id);
        // Generate VCF content
    $vcfContent = "BEGIN:VCARD\n";
    $vcfContent .= "VERSION:3.0\n";
    $vcfContent .= "FN:" . $user->name . "\n";
    $vcfContent .= "TEL;TYPE=HOME,VOICE:" . $user['phone'] . "\n";
    $vcfContent .= "EMAIL:" . $user['email'] . "\n";
    $vcfContent .= "END:VCARD\n";

    // Define the file name
    $fileName = 'contact_' . $id . '.vcf';

    // Set the headers to force download
    header('Content-Type: text/vcard');
    header('Content-Disposition: attachment; filename="' . $fileName . '"');
    header('Content-Length: ' . strlen($vcfContent));

    // Output the VCF content
    echo $vcfContent;

    // Stop further execution (optional, ensures the script doesn't continue)
    exit;
    }
    public function store(Request $request)
    {
        $jsonStr = file_get_contents('php://input'); 
        $jsonObj = json_decode($jsonStr); 
        $contact_data = $jsonObj->contact_data; 

        $contact=new Contact;
        $contact->name=$contact_data[0];
         $contact->email=$contact_data[1];
         $contact->phone=$contact_data[2];
         $contact->save();
         return response()->json([
            'status' => '1',
        ]);

    }
}
?>

7 Create view (Blade)

In the resources/viewsdirectory, create contact.blade.php for the main view:
    
   <!DOCTYPE html>
<html>
<head>
    <title> Create a vCard File in Laravel 11 : A Step-by-Step Tutorial - getsamplecode.com</title>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.0.1/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.datatables.net/1.11.4/css/dataTables.bootstrap5.min.css" rel="stylesheet">
    <script src="https://code.jquery.com/jquery-3.5.1.js"></script>
    <script src="https://cdn.datatables.net/1.10.22/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.10.22/js/dataTables.bootstrap5.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

</head>
<body>

<div class="container">
    <div class="card mt-5">
        <h3 class="card-header p-3"> Create a vCard File in Laravel 11 : A Step-by-Step Tutorial  - getsamplecode.com
        <button type="button" class="btn btn-dark btn-sm" onClick="addContact()">
                    Add Contact
                </button>

        </h3>
        <div class="card-body">
            <table class="table table-bordered " id="contacttable">
                <thead>
                    <tr>
                        <th>No</th>
                        <th>Name</th>
                        <th>Email</th>
                        <th>Phone</th>
                        <th>Created At</th>
                        <th>Action</th>
                    </tr>
                </thead>
                <tbody>
                @foreach($contacts as $contact)
                <tr>
                    <td>{{ $contact->id }}</td>
                    <td>{{ $contact->name }}</td>
                    <td>{{ $contact->email }}</td>
                    <td>{{ $contact->phone }}</td>
                   <td>{{ $contact->created_at }}</td>
                    <td>
                    <a class="btn btn-success" href="exportvcard/{{ $contact->id }}" target="_blank">Download VCard</a>
                    
                    </td>
                </tr>
                @endforeach 
                </tbody>
            </table>
        </div>
    </div>
</div>

</body>

<script type="text/javascript">
  $(document).ready(function() {
            $('#contacttable').DataTable({});
        });
  function addContact()
        {

            (async () => {
      const { value: formValues } = await Swal.fire({
        title: 'Add Contact',
        confirmButtonText: 'Submit',
        showCloseButton: true,
		    showCancelButton: true,
        html:
          '<input id="name" class="swal2-input" placeholder="Enter Name">' +
          '<input id="email" class="swal2-input" placeholder="Enter Email Id">' +
          '<input id="phone" class="swal2-input" placeholder="Enter Phone No">',
        focusConfirm: false,
        preConfirm: () => {
          return [
            document.getElementById('name').value,
            document.getElementById('email').value,
            document.getElementById('phone').value
          ]
        }
      });

      if (formValues) {
        // Add event
        fetch("/store", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({"_token": "{{ csrf_token() }}",  contact_data: formValues}),
        })
        .then(response => response.json())
        .then(data => {
          if (data.status == 1) {
            Swal.fire('Contact added successfully!', '', 'success');
            window.location.reload();
          } else {
            Swal.fire(data.error, '', 'error');
          }

          // Refetch events from all sources and rerender
          calendar.refetchEvents();
        })
        .catch(console.error);
      }
    })()

            
        }
</script>
</html>
    

8 Define Routes

In routes/web.php, define the necessary routes:

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\ContactController;


Route::get('/', function () {
    return view('welcome');
});

Route::get('contacts',[ContactController::class,'index'])->name('contacts.index');
Route::get('exportvcard/{id}', [ContactController::class, 'exportvcard']);
Route::post('/store',[ContactController::class,'store']);


9 Folder Structure

      =
      • =

10 Run Laravel Server to Test the App

Use the following command to serve the Laravel app:

php artisan serve

11 Conclusion

This guide walked you through How to Dynamically Create a vCard File Using Laravel 11 app.

Tags