How to add subject in laravel mail
In Laravel, you can add a subject to a mail by using the subject
method when sending a mail. Here are a few ways to do it:
Method 1: Using the subject
method
Mail::to('[email protected]')->send(new MyMail());
In your MyMail
class, you can define the subject as follows:
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
class MyMail extends Mailable
{
use Queueable, SerializesModels;
public function build()
{
return $this->subject('Hello, World!');
}
}
Method 2: Using the withSubject
method
Mail::to('[email protected]')->withSubject('Hello, World!')->send(new MyMail());
Method 3: Using the subject
property in the mail class
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
class MyMail extends Mailable
{
use Queueable, SerializesModels;
public $subject = 'Hello, World!';
public function build()
{
return $this->subject($this->subject);
}
}
In all cases, the subject will be set to "Hello, World!" when sending the mail.
You can also use placeholders in the subject by using the __
syntax:
public function build()
{
return $this->subject(__('Hello, {{ name }}!'));
}
This will replace {{ name }}
with the actual value of the name
variable in your mail class.
Remember to update your mail class and the subject will be sent with the mail.