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

reese88's avatar

PHP Timeout, Eloquent relationship references parent model

Im experiencing a php timeout error because it takes more than 30 seconds. I have a model (person) that hasMany (connections) which eager loads a hasOne (person) in the connections model. The timeout only occurs on the hasOne (Person) in the connections model. If I change the hasOne in the connections model to use another model instead of person, it works fine. I have experienced this before when a relationship references the original (parent) model, but if it references something else, it works fine too.

0 likes
6 replies
reese88's avatar
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Notifications\Notifiable;
class Person extends Model
{

    use SoftDeletes;

    /**
    * The accessors to append to the model's array form.
    *
    * @var array
    */
   protected $with = ['connections'];

   
    /**
     * Get the connections associated with person.
     */
    public function connections()
    {
        return $this->hasMany('App\Models\Person\Connection', 'from_person_id', 'id')->orderBy('created_at', 'desc');
    }
}

<?php

namespace App\Models\Person;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Notifications\Notifiable;

class Connection extends Model
{
    
    /**
     * The relations to eager load on every query.
     *
     * @var array
     */
    protected $with = ['from_person'];



   /**
    * Get the person associated with id.
    */
   public function from_person()
   {
       return $this->hasOne('App\Models\Person', 'id', 'from_person_id');
   }
}
reese88's avatar

So the from_person relationship in connections only times out when it uses the Person model, if it used any other model, it will work fine.

marin246's avatar

I have encountered the same issue running 5.6.39.. haven't found a solution besides the workaround reloading the model ($yourModel->fresh())

lostdreamer_nl's avatar

ok, so both of your models are loading the other model....

class Person extends Model {
   protected $with = ['connections'];
}
class Connection extends Model {
   protected $with = ['from_person'];
}

It looks to me like the following: Whenever you now load a Person, it will auto load it's connections, which will autoload the Person, which will autoload it's connections, which will autoload the Person, etc....... Recursion much?

It's timing out because it's trying to do an unlimited amount of SQL queries.

Remove either of your protected $with = [...]; to stop this.

[edit] Did not see that the original question was from 16 months ago.... Maybe marin246 is helped by this answer.

2 likes

Please or to participate in this conversation.