ignaMani's avatar

Same relationship works in one event listener but not in the other one which is the same.

Hello I'm facing a problem that I can't understand why is happening. I have this 2 listeners which are the same.

<?php

namespace App\Listeners;


use App\Events\TargetCompleted;
use App\Notifications\TargetCompletedContactNotification;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Support\Facades\Notification;

class SendTargetCompletedContactNotification
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  \App\Providers\TargetCompleted  $event
     * @return void
     */
    public function handle(TargetCompleted $event)
    {
        dd($event->client->contacts);
        foreach($event->client->contacts as $contact) {
            $contact->notify(new TargetCompletedContactNotification($event->kpi, $event->points));
        }
    }
}

<?php

namespace App\Listeners;

use App\Events\TargetAssigned;
use App\Notifications\TargetAssignedContactNotification;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Support\Facades\Notification;

class SendTargetAssignedContactNotification
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  \App\Providers\TargetAssigned  $event
     * @return void
     */
    public function handle(TargetAssigned $event)
    {
        dd($event->client->contacts);
        foreach ($event->client->contacts as $contact) {
            $contact->notify(new TargetAssignedContactNotification($event->kpi, $event->causer));
        }
    }
}

What I do not understand is that in SendTargetCompletedNotification when trying to access $event->client->contacts I get the error Undefined property: Illuminate\Database\Eloquent\Relations\BelongsTo::$contacts but doing the same in SendTargetAssignedContactNotification works. Also if I access $client->contacts before entering SendTargetCompletedNotification It returns the contacts, so it should work apparently.

0 likes
1 reply
tisuchi's avatar

@ignamani It seems you are trying to access some property that is not defined yet.

You can use this:

public function __construct(Client $client, Kpi $kpi, int $points)
{
    $this->client = $client->with('contacts');
    $this->kpi = $kpi;
    $this->points = $points;
}

Please or to participate in this conversation.