Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

reviewdevs's avatar

Exporting some logic to a class caused a mutability issue

Hello, I exported some logic for booking a user into a session into a class called Booker

before I directly attached the user into the session (they have a many to many relationship) now I wanted to export them into their own class to do some logic and possibly through exceptions in case the user can't book this session

here is the code

class Booker extends Controller
{

    static public function book(Session $session, User $user) {
        self::makeSureSessionIsBookable($session, $user);
        $session->attendees()->attach($user);
    }

    private static function makeSureSessionIsBookable(Session $session, User $user)
    {
        if ($session->attendees->count() >= $session->limit) throw new NoMoreSlotsToBookException();
    }
}

when I dd($session->attendees) after the attach, it shows nothing has been attached, even tho it is reflected in the database

am not sure what is the problem here

0 likes
2 replies
intossh@gmail.com's avatar
Level 7

I think you have to refresh the $session model by calling $session->refresh() after the attach() method if you want to see the attached items via the magic property directly after the attach call.

This happens because the foreign id is not stored directly in the model, so the magic property can't see it right away without reading the pivot table again to see what models are actually attached.

If you don't want to call the refresh() method on the model, you can do dd($session->attendees()->get()) and it should work aswell.

Please or to participate in this conversation.