before the Mail, try adding $user->refresh();
Sending email during Import: No query results for model [App\User]
I have the following Import function:
public function collection(Collection $rows)
{
foreach($rows as $row)
{
if(User::where('email', $row['email'])->first() == null)
{
$user = User::create([
//
'name' => $row['name'],
'email' => Str::lower($row['email']),
'password' => Hash::make(Str::random(10)),
]);
$role = $row['role'];
$location = $row['location'];
$user->roles()->attach($role);
$user->hospital()->attach($location);
$token = app('auth.password.broker')->createToken($user);
Mail::to($user)->queue(new NewAccount($user, $token));
}
sleep(2);
}
}
In my local environment this works perfect. In production the email part of this loop is failing (and I know emails work, I've tested them with password resets etc.).
In Laravel Horizon it shows:
ID 111
Queue default
Tags App\User:207
Failed At 2021-03-04 15:18:16
And it gives this error:
Illuminate\Database\Eloquent\ModelNotFoundException: No query results for model [App\User]
The NewAccount Mail is:
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;
use App\User;
class NewAccount extends Mailable implements ShouldQueue
{
use Queueable, SerializesModels;
/**
* Create a new message instance.
*
* @return void
*/
public $user;
public $token;
public function __construct(User $user, $token)
{
//
$this->user = $user;
$this->token = $token;
}
/**
* Build the message.
*
* @return $this
*/
public function build()
{
return $this->markdown('emails.setpassword');
}
}
The only difference between local and production that I can think of is the use of Redis for queue. In my local environment I'm not using Redis.
Any ideas why this may be failing? I should add that this mail class is used for normal registration and works without issue.
is this part of laravel excel import?
The entire import is automatically wrapped in a database transaction, that means that every error will rollback the entire import. When using batch inserts, only the current batch will be rollbacked.
If so, then what is happening is that the queue is starting the job but the transaction has not yet been committed to the database, so outside the function you have here, these users do not exist.
https://docs.laravel-excel.com/3.1/imports/validation.html#disable-transactions
or delay your mail jobs until after the import is complete.
Please or to participate in this conversation.