0

Given my Models Person and Student. Now, one of my controller is doing this:

$person_id = \App\Models\Person::insertGetId(['name' => $request->name, ...]);
\App\Models\Student::create(['person_id' => $person_id, ...]);
$student = \App\Models\Student::where('person_id', $person_id)->first();
dd($student);

During execution, everything has been save but My problem is why i am receiving null on die and dump?

By the way, my student tables' primary and foreign key is the person_id column.

Edit

class Student extends Model
{
    protected $fillable = ['section', 'current_year'];//there are other attribute here which I didn't show because I am using mobile

    public function person(){
       return $this->belongsTo('App\Models\Person', 'person_id', 'id');
    }

    ...
}
11
  • So, to be clear, you save a person, and receive a person_id, you save a student, and he has this person_id, but you cannot find the student using this person_id? Are you sure your new student contains this person_id? Commented Apr 16, 2020 at 8:19
  • Yes, My student table has been populated with person_id. I don't know why I was not able to retrieve. Commented Apr 16, 2020 at 8:21
  • Can you show us the Student model?:) Commented Apr 16, 2020 at 8:22
  • What's happening in \App\Models\Person::insertGetId() ? Commented Apr 16, 2020 at 8:33
  • 1
    you are missing person_id in fillable. Commented Apr 16, 2020 at 8:35

1 Answer 1

2

Add person_id in $fillable property:

protected $fillable = ['section', 'current_year', 'person_id'];
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.