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

siewlon6093's avatar

PHP Notice: Undefined variable: threads in Psy Shell code on line 1

$threads->each(function($thread){ factory('App\Reply', 10)->create([ 'thread_id' => $thread->id ]); });

what error??

$factory->define(App\Reply::class, function (Faker $faker) {
    return [
        'thread_id' => function () {
            return factory('App\Thread')->create()->id;
        },

        'user_id' => function () {
            return factory('App\User')->create()->id;
        },
        'body' => $faker->paragraph
    ];
});
0 likes
8 replies
siewlon6093's avatar
public function index()
    {
        $threads = Thread::latest()->get();

        return view('threads.index', compact('threads'));
    }

threadsController.php

sauravs012's avatar

No need to use get()

public function index()
    {
        $threads = Thread::latest();

        return view('threads.index', compact('threads'));
    }

If you want a single record

public function index()
    {
        $threads = Thread::latest()->first();

        return view('threads.index', compact('threads'));
    }
siangboon's avatar

where this was called?

$threads->each(function($thread){ factory('App\Reply', 10)->create([ 'thread_id' => $thread->id ]); });

you able to get the $threads collection before this?

Snapey's avatar

in tinker, you need to also run the database query. Tinker is telling you that it does not know what $threads is

siangboon's avatar

can screenshot how all the commands are called..

Mahmoud_Awad's avatar

use alternative command like:

$threads=Thread::all();

$threads->each(function($thread){ factory('App\Reply', 10)->create([ 'thread_id' => $thread->id, 'user_id' => $thread->user_id ]); });
1 like

Please or to participate in this conversation.