search

Home  >  Q&A  >  body text

PHP documentation for conditional polymorphic calls

<p>For $item, there is a polymorphic recordable relationship. In the database, this is stored in the loggable_type and loggable_id fields in the items table (for PHP 8 and Laravel). </p> <pre class="brush:php;toolbar:false;">for($items as $item) { // ... if ($item->loggable_type === Comment::class) { $item->loggable->resetDates(); } // ... } </pre> <p>I'm trying to type-hint a loggable in a condition, specifying it as a Comment type. I tried using @var, but writing it like /* @var $item->loggable Comment */ doesn't work, and I can't use /* @var $item Comment */ because that sets the type hint for $item rather than its properties.
P粉127901279P粉127901279474 days ago519

reply all(1)I'll reply

  • P粉063039990

    P粉0630399902023-08-07 00:09:49

    Assign it to a variable

    for($items as $item) {
        if ($item->loggable_type === Comment::class) {
            /** @var Comment $loggable */
            $loggable = $item->loggable;
            
            $loggable->resetDates();
        }
    } 

    reply
    0
  • Cancelreply