Search code examples
phplaravellaravel-maillaravel-controller

Laravel sending custom email


I don't know if this is possible

I am trying to send custom email all the users from my users table. I am using the mail fascades present in laravel.

There is a blade template like this :

@component('mail::message')
# New Book Lunch
 
This is the body of the email.

@component('mail::button', ['url' => $url ?? ''])
View Order
@endcomponent

Thanks,<br>
{{ config('app.name') }}
@endcomponent

My method to send mail looks like this

class NewsLetterController extends Controller
{

    public function newsletter(Request $request)
    {
        $subject = $request->name;
        $message = $request->message;

        $email = User::pluck('email');
        Mail::to($email)->(Add my custom $message and $subject)->send(new NewsLetter());
    }


}

Here I want to add a custom message and subject my filling a form. How can that be done so I can add custom message?


Solution

  • Looking at the docs: https://laravel.com/docs/8.x/mail#sending-mail

    You can pass the variables to the Mailable via the constructor.

    Mail::to($request->user())->send(new NewsLetter($subject, $message));
    

    And in the Mailable:

    class NewsLetter extends Mailable
    {
        // ...
    
        public function __construct(string $subject, string $message) 
        {
           $this->subject = $subject;
           $this->message = $message;
        }
    }
    

    If you want to pass the message to the view, your build could look like:

    class NewsLetter extends Mailable
    {
        // ...
    
        public function build()
        {
            return $this->view('emails.newsletter')
                ->with([
                    'message' => $this->message,
                ]);
        }
    }
    

    And finally, you add the message in blade:

    <p>{{ $message }}</p>