Skip to content
Advertisement

Laravel : Fetch contact form data into notification facade mail

Just made a contact me form on my website and I would like to send an email to the website’s admin when someone sends a message. I’m using the Notification Façade in Laravel to do so, I managed to send the email but I can’t fetch the contact form’s data in the mail. How can I achieve that ?

ContactController.php

class ContactController extends Controller
{
    public function index() {
        return view('contact.index');
    }
    public function store(Request $request, Contact $contact) {
        $validatedAttributes = request()->validate([
            'email' => ['required', 'email:rfc,dns'],
            'subject' => 'required',
            'content' => 'required'
        ]);

        $contact->create($validatedAttributes);

        $user = User::role('super-admin')->select('email')->first();

        $user->notify(new ContactReceived(), $contact);


        return response()->json('Message sent.');
    }
}

class ContactReceived extends Notification
{
    use Queueable;


    public function __construct()
    {
    }


    public function via($notifiable)
    {
        return ['mail'];
    }


    public function toMail($notifiable)
    {

        return (new MailMessage)
                ->subject('subject')
                ->greeting('Hello,')
                ->line('some line');
    }
    public function toArray($notifiable)
    {
        return [
            //
        ];
    }
}

Advertisement

Answer

Just pass your contact into constructor:

public function store(Request $request) {
    $validatedAttributes = request()->validate([
        'email' => ['required', 'email:rfc,dns'],
        'subject' => 'required',
        'content' => 'required'
    ]);

    $contact = Contact::create($validatedAttributes); // create contact

    $user = User::role('super-admin')->select('email')->first();

    $user->notify(new ContactReceived($contact)); // pass contact into notification

    return response()->json('Message sent.');
}

There, in notification, you also have to add property and process it in constructor

class ContactReceived extends Notification
{
    private $contact;
    
    public function __construct(Contact $contact)
    {
        $this->contact = $contact;
    }

    public function toMail($notifiable)
    {
        // $this->contact is accessible anywhere in the notification
    }
}

Then you can use $this->contact in notification.

More info you can find here.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement