phplaravelformsoctobercms

October CMS | Using a button to send email retrieved from a field


I'm trying to dynamically find email address (from what has been inputted in a field), then sending out email to that address.

So far, I have been able to get the button to send emails but unable to retrieve the address from model.

Examples:

Controller

public function onSend()

{  
   // Retrieve email address from Machines model in email field
   $this->vars['email'] = Machines::get('email');

   // Send to email address using partial button
   Mail::send('martin.maintenance::mail.maintenancereminder', [], function($message) {
      $message->to($this->vars['email']);
   });
}

Field (in Machines model)

email:
  label: 'Email Address'
  span: auto
  type: text
  tab: Details

Partial (button)

<button
    type="submit"
    data-request="onSend"
    class="btn btn-primary">
    Reminder
</button>

Error enter image description here

Happy to provide any additional info. Thanks in advance!


Solution

  • I'm not sure what part of your code is triggering that error, but I suspect it has something to do with what ::get('email') is returning.

    Machines::get('email') returns a Collection of Machines instances like this:

    Illuminate\Database\Eloquent\Collection {#4744
      all: [
        App\Models\Machines {#4745
          email: "example@example.com",
        },
        App\Models\Machines {#4746
          email: "example2@example.com",
        },
        // ...
      ]
    }
    

    If you want all of the email column values in an Array/Collection, do this:

    $this->vars['email'] = Machines::pluck('email');
    

    Machines::pluck('email') returns a Collection of strings like this:

    Illuminate\Support\Collection {#4516
      all: [
        "example@example.com",
        "example2@example.com",
        // ...
      ]
    }
    

    If you explictly need an array, you can do:

    $this->vars['email'] = Machines::pluck('email')->toArray();
    /*
     * [
     *   "example@example.com",
     *   "example2@example.com",
     *   // ...
     * ]
     */
    

    Also, sidenote, Model names in Laravel are by convention singular, so it should be Machine instead of Machines.