No query results for user model when sending emails with Queue Notifications

312 views Asked by At

In Laravel 5.8, there are no query results for Model App\Models\user when sending an email with queued notifications. When the notification is directly sent, there is no problem. But when I used jobs, I received an error about the User Model Not found.

Controller

$notifiables = User::all();

if (count($notifiables) > 0) {
    Notification::send($notifiables, new NewTrainingNotificationUser(Training::find($id)));
}

Notification class

class NewTrainingNotification extends Notification implements ShouldQueue
{
    use Queueable;

    public function via($notifiable)
    {
        return ['database', 'mail'];
    }

    public function toMail($notifiable)
    {
        return (new MailMessage)
            ->from(env("MAIL_FROM_ADDRESS"), env('SMS_TOPIC'))
            ->subject("Nouvelle formation ajoutée.")
            ->greeting('Bonjour ' . $notifiable->lastname . ' ' . $notifiable->firstname . ',')
            ->line('La formation (' . $this->training->title . ') a été ajoutée pour votre équipe.')
            ->line("Team " . env('SMS_TOPIC'))
            ->salutation('Cordialement,');
    }
}

And here is the error I received in the failed_job table

Stack trace:
#0 /var/www/html/otd/vendor/laravel/framework/src/Illuminate/Queue/SerializesAndRestoresModelIdentifiers.php(85): Illuminate\Database\Eloquent\Builder->firstOrFail()
#1 /var/www/html/otd/vendor/laravel/framework/src/Illuminate/Queue/SerializesAndRestoresModelIdentifiers.php(55): Illuminate\Notifications\SendQueuedNotifications->restoreModel(Object(Illuminate\Contracts\Database\ModelIdentifier))
#2 /var/www/html/otd/vendor/laravel/framework/src/Illuminate/Queue/SerializesModels.php(45): Illuminate\Notifications\SendQueuedNotifications->getRestoredPropertyValue(Object(Illuminate\Contracts\Database\ModelIdentifier))
#3 [internal function]: Illuminate\Notifications\SendQueuedNotifications->__wakeup()
#4 /var/www/html/otd/vendor/laravel/framework/src/Illuminate/Queue/CallQueuedHandler.php(42): unserialize('O:48:"Illuminat...')
#5 /var/www/html/otd/vendor/laravel/framework/src/Illuminate/Queue/Jobs/Job.php(83): Illuminate\Queue\CallQueuedHandler->call(Object(Illuminate\Queue\Jobs\DatabaseJob), Array)
#6 /var/www/html/otd/vendor/laravel/framework/src/Illuminate/Queue/Worker.php(327): Illuminate\Queue\Jobs\Job->fire()
#7 /var/www/html/otd/vendor/laravel/framework/src/Illuminate/Queue/Worker.php(277): Illuminate\Queue\Worker->process('database', Object(Illuminate\Queue\Jobs\DatabaseJob), Object(Illuminate\Queue\WorkerOptions))
#8 /var/www/html/otd/vendor/laravel/framework/src/Illuminate/Queue/Worker.php(118): Illuminate\Queue\Worker->runJob(Object(Illuminate\Queue\Jobs\DatabaseJob), 'database', Object(Illuminate\Queue\WorkerOptions))
#9 /var/www/html/otd/vendor/laravel/framework/src/Illuminate/Queue/Console/WorkCommand.php(102): Illuminate\Queue\Worker->daemon('database', 'default', Object(Illuminate\Queue\WorkerOptions))
#10 /var/www/html/otd/vendor/laravel/framework/src/Illuminate/Queue/Console/WorkCommand.php(86): Illuminate\Queue\Console\WorkCommand->runWorker('database', 'default')
#11 [internal function]: Illuminate\Queue\Console\WorkCommand->handle()
#12 /var/www/html/otd/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(29): call_user_func_array(Array, Array)
#13 /var/www/html/otd/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(87): Illuminate\Container\BoundMethod::Illuminate\Container\{closure}()
#14 /var/www/html/otd/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(31): Illuminate\Container\BoundMethod::callBoundMethod(Object(Illuminate\Foundation\Application), Array, Object(Closure))
#15 /var/www/html/otd/vendor/laravel/framework/src/Illuminate/Container/Container.php(572): Illuminate\Container\BoundMethod::call(Object(Illuminate\Foundation\Application), Array, Array, NULL)
#16 /var/www/html/otd/vendor/laravel/framework/src/Illuminate/Console/Command.php(183): Illuminate\Container\Container->call(Array)
#17 /var/www/html/otd/vendor/symfony/console/Command/Command.php(255): Illuminate\Console\Command->execute(Object(Symfony\Component\Console\Input\ArgvInput), Object(Illuminate\Console\OutputStyle))
#18 /var/www/html/otd/vendor/laravel/framework/src/Illuminate/Console/Command.php(170): Symfony\Component\Console\Command\Command->run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Illuminate\Console\OutputStyle))
#19 /var/www/html/otd/vendor/symfony/console/Application.php(1009): Illuminate\Console\Command->run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#20 /var/www/html/otd/vendor/symfony/console/Application.php(273): Symfony\Component\Console\Application->doRunCommand(Object(Illuminate\Queue\Console\WorkCommand), Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#21 /var/www/html/otd/vendor/symfony/console/Application.php(149): Symfony\Component\Console\Application->doRun(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#22 /var/www/html/otd/vendor/laravel/framework/src/Illuminate/Console/Application.php(89): Symfony\Component\Console\Application->run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#23 /var/www/html/otd/vendor/laravel/framework/src/Illuminate/Foundation/Console/Kernel.php(122): Illuminate\Console\Application->run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#24 /var/www/html/otd/artisan(37): Illuminate\Foundation\Console\Kernel->handle(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#25 {main}```

Please, has anyone encountered this error before?
1

There are 1 answers

0
enrique Abbey On

Hi Paladin here is my whole user.php file


namespace App\Models;

use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Support\Facades\Cache;
use Tymon\JWTAuth\Contracts\JWTSubject;
use Zizaco\Entrust\Traits\EntrustUserTrait;

//use Laravel\Passport\HasApiTokens;

class User extends Authenticatable implements JWTSubject
{
    use Notifiable;

    //use HasApiTokens, Notifiable;

    use SoftDeletes {
        restore as private restoreA;
    }
    use EntrustUserTrait {
        restore as private restoreB;
    }

    public function restore()
    {
        $this->restoreA();
        $this->restoreB();
    }

    /**
     * The attributes that aren't mass assignable.
     *
     * @var array
     */
    protected $guarded = [];

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    /*protected $fillable = [
        'slug',
        'firstname',
        'lastname',
        'username',
        'email',
        'email_verified_at',
        'phone',
        'country_id',
        'password',
        'reset_password_token',
        'reset_password_token_end_at',
    ];*/

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

    /*
    public static function boot()
    {
        parent::boot();

        static::saving(function ($model) {
            //dd($model->slug);
            $model->slug = str_slug('slug-' . $model->id);
            //$model->slug = uniqid().strtotime("now");
        });
    }
    */


    public function getQualifiedKeyName()
    {
        return 'slug';
    }


    /**
     * Get the identifier that will be stored in the subject claim of the JWT.
     *
     * @return mixed
     */
    public function getJWTIdentifier()
    {
        return $this->getKey();
    }

    /**
     * Return a key value array, containing any custom claims to be added to the JWT.
     *
     * @return array
     */
    public function getJWTCustomClaims()
    {
        return [];
    }


    /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function team()
    {
        return $this->belongsTo('App\Models\Team');
    }

    /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function fonction()
    {
        return $this->belongsTo('App\Models\Fonction');
    }

    /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function media()
    {
        return $this->belongsTo('App\Models\Media');
    }

    /**
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function messageUsers()
    {
        return $this->hasMany('App\Models\MessageUser');
    }

    /**
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function comments()
    {
        return $this->hasMany('App\Models\Comment');
    }

    /**
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function trainingUsers()
    {
        return $this->hasMany('App\Models\TrainingUser');
    }

    /**
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function evaluationUsers()
    {
        return $this->hasMany('App\Models\EvaluationUser');
    }

    public function isOnline()
    {
        return Cache::has('user-is-online' . $this->id);
    }

    public function region(){
        return $this->hasOne(Region::class, 'user_id');
    }

    public function getTeamTrainingsAttribute(){
        if (isset($this->attributes['team_id'])){
            return TrainingTeams::query()->where('team_id', '=', $this->attributes['team_id'])
                ->select('training_id')->get();
        }
        return [];
    }

    public function getNomComplet(){
        return $this->firstname.' '.$this->lastname;
    }

    public function fullName(){
      return $this->getNomComplet();
    }
}```