Home > Mobile >  How to use store Controller method in Laravel, when class extends another?
How to use store Controller method in Laravel, when class extends another?

Time:12-22

I have class User that has variables like name, surname, email... and classes Student and Teacher that extend User. Let's just focus on Student class.

I want to create student (create so that he's in database) with:

<form method="post" action="{{ route('students.store') }}">
@csrf
        <div>
            <x-input-label for="name" :value="__('Name of student')" />
            <x-text-input id="name" type="text" name="name" :value="old('name')" autofocus />
            <x-input-error :messages="$errors->get('name')"  />
        </div>

        ...

        <x-primary-button>
             {{ __('Create') }}
        </x-primary-button>
</form>

But the problem is, there are no name, surname... variables in Student class, they are in User class. Laravel tries to put everything in SQL table students. (Error: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'name' in 'field list')

What do I have to do? How to create objects of classes that inherit from other classes in Laravel? Maybe extend students table in database so that it has these variables?

edit: Student class may have variables like: classes, frequency...

CodePudding user response:

If your Student class extends the User class, you need to specify the table the Student class is using, otherwise, Laravel has to guess the table name based on the model name.

protected $table = 'users';

https://laravel.com/docs/9.x/eloquent#table-names

Edit --

Say you have a Users table like so:

id name surname is_student
1 john doe 0
2 jane smith 1

And a classes table:

id class room
1 Geometry A
2 Physics B

You can connect them via a pivot table (classes_users) to store additional student-specific data:

student_id class_id
2 1
3 1
4 2
  • Related