Search code examples
phplaravellaravel-5laravel-6email-verification

User verification email cannot be sent in laravel


In my laravel base application i have an admin panel where my admin can add new users from the backend.

But I want to send an account activation email to my user once even the admin created the account.

I'm already sending account activation emails when a user register with the system from the front end registration form.

But I am not able to send the activation mail to user when the admin creates an account..

Following is my user model

<?php

namespace App;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Spatie\Permission\Traits\HasRoles;

class User extends Authenticatable implements MustVerifyEmail
{
    use Notifiable;
    use HasRoles;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name','last_name', 'email', 'password','username','mobile','user_roles',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];
}

And my user controller (only the store function is included) as follows

public function store(Request $request)
    {
        request()->validate([
            'name' => ['required', 'alpha','min:2', 'max:255'],
            'last_name' => ['required', 'alpha','min:2', 'max:255'],
            'email' => ['required','email', 'max:255', 'unique:users'],
            'password' => ['required', 'string', 'min:12', 'confirmed','regex:/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{12,}$/'],
            'mobile'=>['required', 'regex:/^\+[0-9]?()[0-9](\s|\S)(\d[0-9]{9})$/','numeric','min:9'],
            'username'=>['required', 'string', 'min:4', 'max:10', 'unique:users'],   
            'roles'=>['required'],
            'user_roles'=>['required'],
        ]);

        //Customer::create($request->all());

        $input = $request->all();
        $input['password'] = Hash::make($input['password']);

        $user = User::create($input);
        $user->assignRole($request->input('roles'));

        return redirect()->route('customers.index')
                        ->with('success','Customer created successfully.');
    }

And in my web.php i have this,

Auth::routes(['verify' => true]);

So currently the user creates successfully but the verification email is not being sent.

How can I send the verification email? where do I need to change?

Thank you.


Solution

  • After creating the user, fire the Registered event with the new user instance.

    event(new Registered($user));