Skip to content
Advertisement

Adding Data to Belongs to resource using TextField laravel Nova

Hi is there any way to insert data in two tables in one request laravel nova belongsTo relation What I am trying to achieve is that I have two models first is the user model & the second one is the student Model User model has email and password And student model has other profiling details of a student when a student is created I need to insert a record in the user’s table as well and relate that inserted entity with my student detail like some entity go into student details and some in user model related with authentications I am trying to achieve this with laravel nova.

HERE IS USER MODEL RELATIONSHIP WITH STUDENTS

 public function students(){
    return $this->hasMany('Appstudent','user_id','id');
}

HERE IS STUDENT MODEL RELATIONSHIP WITH USER

public function user(){
    return $this->belongsTo('AppUser','user_id','id');
}

I also tried to use nova belongs to field but it gives me dropdown with existing users but I want to create user and student both on the fly in one go and link them with each other https://nova.laravel.com/docs/2.0/resources/relationships.html#belongsto

I hope i clarify my point thanks if anything feels free to ask or collaborate thanks

Advertisement

Answer

You can do that inside your model, you need to override the save function:

public function save(array $options = array()) {
    parent::save($options);
}

please note that in order to link your current model to another one, you need to do so after this line parent::save($options); since you can’t get the $this->”primary_key” of the current record before actually saving the model in the database

ex:

class Student
{
    public function save(array $options = array()) {

        $user = new User();
        $user->property1 = '';
        $user->property2 = '';
        $user->save();

        parent::save($options);

        //Here you can get the $this->studentid
        //Or the $user->userid

    }
}
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement