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

TimiAde's avatar

How to use php artisan tinker with relationship

I want to use php tinker to post data into my db, but i am having issues because of the relationships involved.

 public function up()
    {
        Schema::create('questions', function (Blueprint $table) {
            $table->id();
            $table->string('the_question');
            $table->unsignedBigInteger('user_id');
            $table->foreign('user_id')->references('id')->on('users');
            $table->timestamps();
        });
    }
public function up()
    {
        Schema::create('options', function (Blueprint $table) {
            $table->increments('id');
            $table->string('the_option');
            $table->unsignedBigInteger('question_id');
            $table->foreign('question_id')->references('id')->on('questions');
            $table->timestamps();
        });
    }
public function up()
    {
        Schema::create('answers', function (Blueprint $table) {
            $table->increments('id');
            $table->string('correct_answer');
            $table->unsignedBigInteger('question_id');
            $table->foreign('question_id')->references('id')->on('questions');
            $table->timestamps();
        });
    }

or how can i use factory or seeder to go about it. One question with four options and the correct answer

0 likes
3 replies
TimiAde's avatar

@Nakov

public function run()
{
    User::factory()
            ->count(1)
            ->hasQuestions(1)->hasOptions(4)
												->hasAnswer(1)
            ->create();
}

please i dont know how to write it since laravel only gives a single example

Please or to participate in this conversation.