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

wim91's avatar
Level 2

How can I adapt a Laravel query?

There are 3 tables with a relationship: Test1, Test2, Test3. They contain primitive data, the "name" and "desc" fields. Connected one to many: Test1(id)->Test2(test2_id), Test2(id)->Test3(test3_id).

I unload data from them using the hasMany connection like this:

public function method1() { return $this->hasMany(Test2::class, 'test2_id', 'id')->with('method2'); }

Method 2 is like this:

public function method2(){ return $this->hasMany(Test3::class, 'test3_id', 'id'); }

Everything is stretched out for me, there aren’t even that many requests, but a lot of memory is allocated, i.e. The debugger shows a large number of calls to models, although there are only about 10 records... I add records, the number of models increases in the request.

Tell me how to optimize the query? Preferably through Eloquent.

0 likes
2 replies
Snapey's avatar

make it real, we cant diagnose psuedo code

wim91's avatar
Level 2

@Snapey Ok, I'll add it now

These are my migrations ​

Here are my models and methods in them


namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Test1 extends Model
{
    use HasFactory;

    public function method1(){
       return $this->hasMany(Test2::class, 'test2_id', 'id')->with('method2');
   }
namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Test2 extends Model
{
    use HasFactory;

    public function method2(){
      return $this->hasMany(Test3::class, 'test3_id', 'id');
    }
}

Here's controller

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Test1;


class HomeController extends Controller
{
 
    public function index()
    {
         $res= Test1::with('method1')->get();
           return view('home' , compact(['res']));
    }
}

The tables are filled with test data, no more than 10 records... At the same time, through the debugger it shows 5 queries and 20 models... If you add records, the number of queries remains 5, and the number of models increases... Moreover, if there are about 1000 records, then There will be more than 10,000 models... Is it possible to optimize this somehow? How?

Please or to participate in this conversation.