Génération de QRCode Laravel

De Gandal
Révision datée du 11 juin 2024 à 15:35 par Abdoulaye (discussion | contributions) (Page créée avec « <nowiki>https://github.com/endroid/qr-code</nowiki> SimpleSoftwareIO/simple-qrcode: An easy-to-use PHP QrCode generator with first-party support for Laravel. (github.com) <syntaxhighlight lang="php"> <?php namespace App\Http\Controllers; use App\Mail\TicketPurchased; use App\Models\Participant; use App\Models\Ticket; use Illuminate\Http\Request; use Illuminate\Http\JsonResponse; use Illuminate\Support\Facades\Mail; use SimpleSoftwareIO\QrCode\Facades\QrCode;... »)
(diff) ← Version précédente | Voir la version actuelle (diff) | Version suivante → (diff)

https://github.com/endroid/qr-code

SimpleSoftwareIO/simple-qrcode: An easy-to-use PHP QrCode generator with first-party support for Laravel. (github.com)

<?php

namespace App\Http\Controllers;

use App\Mail\TicketPurchased;
use App\Models\Participant;
use App\Models\Ticket;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Mail;
use SimpleSoftwareIO\QrCode\Facades\QrCode;

class TicketController extends Controller
{
    /**
     * Purchase a ticket
     *
     * @param Request $request
     * @response array{message: "Ticket purchased successfully and email sent."}
     * @return JsonResponse
     */
    public function purchase(Request $request)
    {
        // Generate a unique code for the ticket
        $ticketCode = uniqid();

        // Generate a link to validate the ticket
        $qrCodeUrl = route('validate.ticket', ['code' => $ticketCode]);
        
        // Generate QR code with the link
        $qrCode = QrCode::format('png')->size(200)->generate($qrCodeUrl);

        // Create ticket
        $ticket = Ticket::create([
            'type' => $request->type,
            'price' => $request->price,
            'code' => $ticketCode,
            'qr_code' => base64_encode($qrCode),
            'status' => 'unvalidated',
            'event_id' => $request->event_id,
            'participant_id' => $request->participant_id,
        ]);

        // Send email with QR code
        $participant = Participant::find($request->participant_id);
        Mail::to($participant->email)->send(new TicketPurchased($ticket));

        return response()->json(['message' => 'Ticket purchased successfully and email sent.', 'ticketCode' => $ticketCode, 'qrCode' => $qrCodeUrl], 201);
    }
}