How to call mail in laravel 5.6
In Laravel 5.6, you can use the Mail
facade to send emails. Here are the steps:
Step 1: Create a mail class
Create a new PHP class in the app/Mail
directory, e.g., WelcomeEmail.php
. This class should extend the Illuminate\Mail\Mailable
class.
// app/Mail/WelcomeEmail.php
namespace App\Mail;
use Illuminate\Mail\Mailable;
class WelcomeEmail extends Mailable
{
public function build()
{
return $this->view('emails.welcome');
}
}
Step 2: Define the email view
Create a new Blade view in the resources/views/emails
directory, e.g., welcome.blade.php
.
<!-- resources/views/emails/welcome.blade.php -->
Hello, {{ $user->name }}!
Step 3: Use the Mail facade
In your controller or service, use the Mail
facade to send the email.
// app/Http/Controllers/AuthController.php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;
class AuthController extends Controller
{
public function sendWelcomeEmail(Request $request)
{
$user = User::find(1); // Replace with your user model and ID
Mail::to($user->email)->send(new WelcomeEmail($user));
return 'Email sent!';
}
}
Step 4: Configure the mail settings
Make sure you have the necessary mail settings configured in your .env
file:
MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
[email protected]
MAIL_PASSWORD=your_password
MAIL_ENCRYPTION=tls
Replace the values with your actual mail settings.
That's it! When you call the sendWelcomeEmail
method, it will send a welcome email to the specified user.
Remember to update your composer.json
file and run composer dump-autoload
to register the new mail class.