# Quick Dive into Laravel Bento Integration

Hey there! Today, we're diving into the Laravel and Bento integration. By the end of this tutorial, you'll have a Laravel app that is ready to work with Bento and be comfortable with some of the features of the [Bento-laravel-sdk](https://github.com/bentonow/bento-laravel-sdk). Let's get into it. {{ className: 'lead py-6' }}


  
**1. Setting up Your Laravel Environment**

  

    First things first, let's prepare our Laravel environment. I'll begin with a fresh install, though the SDK features work perfectly for mature applications right out of the box as well.


    1. Install Laravel:
    ```bash
    composer create-project laravel/laravel bento-example
    ```

    2. Install dependencies:
    ```bash
    composer require bentonow/bento-laravel-sdk
    ```

    3. Set up Bento:
    ```bash
    php artisan bento:install
    ```

  

  
**2. Configuring Your Environment**

  

    Now, let's configure our app to work with Bento. You can find your `Bento API keys` and `Site_UUID` in the Bento account dashboard, don't share them or commit them to source code.

    If you want to use bento to handle the transactional emails the sdk includes a `transport` for your convenience.

    1. Open your `.env` file and add these lines:
    ```bash
    BENTO_SITE_UUID=your_site_uuid
    BENTO_PUBLISHABLE_KEY=your_publishable_key
    BENTO_SECRET_KEY=your_secret_key
    ```

    2. Update your `config/mail.php` file to use Bento as the mail transport:
    ```php
    'default' => env('MAIL_MAILER', 'bento'),

    'mailers' => [
      // ... other mailers ...
      'bento' => [
        'transport' => 'bento',
      ],
    ],
    ```

    
> I made bento the default mailer via the `mail.php` configuration, but you can of course set this in your `.env` file via the `MAIL_MAILER` key.


    
> The Bento mail transport works just like any other SMTP mail configuration you might be used to. I highly suggest the use of [queues](https://laravel.com/docs/11.x/queues) & something like [supervisor](https://laravel.com/docs/11.x/queues#supervisor-configuration) for the best user experience.


  

  
**3. Creating and Using a Mailable**

  

    Let's create a simple mailable that uses a view and sends it as a Bento Transactional email.

    
> There are many advantages to implementing this use case through a Bento flow, but for this example, let's start simple.


    1. Create a new mailable:
    ```bash
    php artisan make:mail WelcomeMail
    ```

    2. Let's edit `app/Mail/WelcomeMail.php` and make a few additions:
    ```php
    use Illuminate\Bus\Queueable;
    use Illuminate\Mail\Mailable;
    use Illuminate\Queue\SerializesModels;
    use App\Models\User;

    class WelcomeMail extends Mailable
    {
      use Queueable, SerializesModels;

      public function __construct(protected User $user)
      {

      }

      public function build()
      {
        return $this->view('emails.welcome')
          ->to($this->user->email);
      }
    }
    ```

    3. Create a view for the email at `resources/views/emails/welcome.blade.php`:

    ```html
    <h1>Welcome to our Bento Example, {{ $user->name }}!</h1>
    <p>We're excited to have you on board. Get started by exploring our features.
      Or reviewing our documentation at <a href='https://docs.bentonow.com'>docs.bentonow.com</a>
    </p>
    ```

    4. Now, let's use this mailable. For example, let's edit `App\Http\Controllers\Auth\RegisteredUserController`:

    ```php
    use App\Mail\WelcomeMail;
    use Illuminate\Support\Facades\Mail;

    // After creating the user
    $user = User::create([
      'name' => $request->name,
      'email' => $request->email,
      'password' => Hash::make($request->password),
    ]);

    // Send the welcome email
    Mail::to($user->email)->queue(new WelcomeMail($user));
    ```
  
> Notice that I am using a Queue here. This ensures that when the user creates their account, they don't have to wait for the email to be sent. This does require a queue worker to be running.


  


**4. Adding the User to Bento**


  When a user registers, let's add them as a subscriber to Bento. That way we can capture activities the user takes and use them to trigger email flows in bento.

  1. Lets jump back into our `RegisteredUserController`:
  ```php
  use Bentonow\BentoLaravel\BentoConnector;
  use Bentonow\BentoLaravel\DataTransferObjects\CreateSubscriberData;
  use Bentonow\BentoLaravel\Requests\CreateSubscriber;

  // after creating the user:
  $bento = new BentoConnector();

  $data = collect([
    new CreateSubscriberData(email: $user->email)
  ]);
  $request = new CreateSubscriber($data);
  $bento->send($request);
  ```

  
> For mature applications with many pre-existing users, take a look at our [Laravel Importer](/docs/examples/laravel_importer) to help you get started quickly.


**5. Adding a Bento Tag to a User**


  Tags are great ways to segment users. In many email platforms they would be considered lists.

  1. In our example lets tag a new user based on their source (website):

  ```php
  use Bentonow\BentoLaravel\DataTransferObjects\ImportSubscribersData;
  use Bentonow\BentoLaravel\Requests\ImportSubscribers;

  // After we send the email lets tag the user.

  $data = collect([
    new ImportSubscribersData(
      email: $user->email,
      firstName: Str::of($user->name)
        ->after('.')
        ->before(' ')
        ->__toString(),
      lastName: Str::of($user->name)
        ->after(' ')
        ->__toString(),
      tags: ["list:website"],
      removeTags: null,
      fields: null,
    ),
  ]);

  $request = new ImportSubscribers($data);
  $bento->send($request);
  ```


**6. Using Bento fields**


  Tags are great for segmentation, but sometimes we need to store user data to personalize emails. Fields are perfect for this purpose.

  1. Lets record a users favorite color:
  ```php

  // assuming our sign up form included a field for favorite color
  // lets update the previous tag example to include our field data.

  $data = collect([
      new ImportSubscribersData(
          email: $user->email,
          firstName: Str::of($user->name)
            ->after('.')
            ->before(' ')
            ->__toString(),
          lastName: Str::of($user->name)
            ->after(' ')
            ->__toString(),
          tags: ["list:website"],
          removeTags: null,
          fields: ["fav_color" => $request->input('favorite_color')],
      ),
  ]);

  $request = new ImportSubscribers($data);
  $bento->send($request);
  ```

  With Bento's API, you can quickly build a comprehensive subscriber profile, enhancing both targeting and personalized communication—often with just a single API call.

  
> The `ImportSubscribers` method safely merges new fields into a user's data without triggering any flows or events from the data you send.


### Wrapping Up

And there you have it! You've successfully integrated Bento with your Laravel app. You can now manage emails, track user registrations, and even tag users even record custom data into fields for use in emails with the [liquid tags](/docs/liquid_guide).


This is just the beginning – feel free to explore more Bento features and tailor them to your specific needs. Contact us in [discord](https://discord.gg/ssXXFRmt5F) if you need help or have some suggestions!