lundi 28 février 2022

LARAVEL : Passing an id through a form to a foreign key

I'm a beginner with Laravel and I'm a little bit confused with something.So what I'm trying to do is creating a familly through a form , then save this familly and after that we are redirect to a minorstudent form where you can create a student that is link to the familly you just created before.Everything on my models, migrations is okay because in my controller I can see the student and the familly.But my problems is when I create the familly I want to pass the 'id' of the table 'familly' to the table familly which has in its table the foreign key 'familly_id' ...But I dont know how to do it on my controllers.Thanks for the future help.

else {
          $minorstudent = new Minorstudent;
          $minorstudent->first_name = $request->first_name;
          $minorstudent->last_name = $request->last_name;
          $minorstudent->phone_number = $request->phone_number;
          $minorstudent->street_address = $request->street_address;
          $minorstudent->postal_code = $request->postal_code;
          $minorstudent->city = $request->city;
          $minorstudent->email_address = $request->email_address;
          $minorstudent->level = $request->level;
          if ($request->school!="none") {
              $minorstudent->school()->associate($request->school);
          }
          $minorstudent->save();
          return redirect('/familly');
        }

And I want the 'id' of the familly i created before being pass to the minorstudent into 'familly_id' wich is a foreign key.

 else {
        $minorstudent = Minorstudent::where('id',$request->id)->first();
        if ( $request->get('add_student_next') !== null ) {
          $familly = new Familly;
          $familly->first_name = $request->first_name;
          $familly->last_name = $request->last_name;
          $familly->phone_number = $request->phone_number;
          $familly->street_address = $request->street_address;
          $familly->postal_code = $request->postal_code;
          $familly->city = $request->city;
          $familly->email_address = $request->email_address;
          $familly->absence = 1;
          $familly->rules = 1;
          $minorstudent->familly_id()->attach($familly); 
          $familly->save();
          return redirect("/familly/id/student/new");
        }
        

This the familly controllers (form) where you create the familly and after that you are redirect to the minorstudent form

ps:Dont worry about the else at the beginning



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire