Creating a contact on Brevo (formerly known as Sendinblue) using Laravel involves several steps, including setting up your Brevo account, obtaining an API key, and integrating it with your Laravel application. Here’s a step-by-step guide to achieve this:
If you haven’t already installed Guzzle, you can do so via Composer. Guzzle is a PHP HTTP client that makes it easy to send HTTP requests.
composer require guzzlehttp/guzzle
Create a service class that will handle the interaction with the Brevo API.
<?php namespace App\Services; use GuzzleHttp\Client; class BrevoService { protected $client; protected $apiKey; public function __construct() { $this->client = new Client([ 'base_uri' => 'https://api.brevo.com/v3/', ]); $this->apiKey = env('BREVO_API_KEY'); } public function createContact($email, $attributes = [], $listIds = []) { $response = $this->client->post('contacts', [ 'headers' => [ 'api-key' => $this->apiKey, 'Content-Type' => 'application/json', 'Accept' => 'application/json', ], 'json' => [ 'email' => $email, 'attributes' => $attributes, 'listIds' => $listIds, ], ]); return json_decode($response->getBody(), true); } }
Add your Brevo API key to your .env
file.
BREVO_API_KEY=your_brevo_api_key
Now, you can use the BrevoService
in your controller to create a contact.
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Services\BrevoService; class ContactController extends Controller { protected $brevoService; public function __construct(BrevoService $brevoService) { $this->brevoService = $brevoService; } public function store(Request $request) { $request->validate([ 'email' => 'required|email', 'first_name' => 'required|string', 'last_name' => 'required|string', ]); $email = $request->input('email'); $attributes = [ 'FIRSTNAME' => $request->input('first_name'), 'LASTNAME' => $request->input('last_name'), 'SMS' => $request->input('phone'), // Add phone number 'WHATSAPP' => $request->input('phone'), // Add whatsapp number ]; $listIds = [/* Your list IDs here */]; $result = $this->brevoService->createContact($email, $attributes, $listIds); return response()->json($result); } }
Add a route to handle the contact creation in your routes/web.php
or routes/api.php
file.
use App\Http\Controllers\ContactController; Route::post('/contacts', [ContactController::class, 'store']);
You can now test the implementation by sending a POST request to /contacts
with the required parameters (email
, first_name
, last_name
). This can be done using tools like Postman or via a frontend form in your application.
{ "email": "john.doe@example.com", "first_name": "John", "last_name": "Doe" }
This setup should allow you to create a contact on Brevo using your Laravel application. Make sure to handle any errors and edge cases according to your application’s requirements.