Sonya
Sonya

Reputation: 47

Laravel store data to the pivot table eloquent

I am trying to store data to the DB from a form. I have table with columns subject, subjectType(Economic, Informatic subject) and subjectType_subject(pivot table). I can store data to Subject table but I need to store id's to subjectType_subject table. In my view I have a dropdown nav - Economic subjects and Informatic subjects. If I would like to add Economic subject, I need to add ID's to pivot table to display it.

How can I do this please?

Now I can store data only to Subject table and it doesn't appear on Economic subjects section:

SubjectController

public function create() {
}

public function store(Request $request)
{
    $this->validate($request, [
        'name' => 'required',
        'abbreviation' => 'required',
        'description' => ''
    ]);

    $subject = new Subject();
    $subject->name = $request->input('name');
    $subject->abbreviation = $request->input('abbreviation');
    $subject->description = $request->input('description');

    $subject->save();

    return redirect()->back()
         ->with('success', 'Úspěšne jsi vytvořil nový předmět.');
    }
}

Subject Model

public $table = 'Subject';

protected $fillable = [
    'name',
    'abbreviation',
    'description'
];

public function subject_type() {
    return $this->belongsToMany('App\Subject_type',  'subjectType_subject');
}

SubjectType Model

public $table = 'SubjectType';

public function subject() {
    return $this->belongsToMany('App\Subject', 'subjectType_subject');
}

Upvotes: 0

Views: 1398

Answers (2)

Kapitan Teemo
Kapitan Teemo

Reputation: 2164

First, try to fix your naming conventions. Things would be a lot easier if you follow laravel's naming convention. Here is the guide.

  • Table Name should be snake_case (change subjectType to subject_type)
  • Pivot Tables should be singular model names in alphabetical order (change subjectType_subject to subject_subject_type)
  • belongsToMany should have a plural function name. (change public function subject_type() to public function subject_types() and also the public function subject() to public function subjects()

Then use laravels attach keyword in order to fill the pivot table.

$subject = new Subject();
$subject->name = $request->input('name');
$subject->abbreviation = $request->input('abbreviation');
$subject->description = $request->input('description');
$subject->save();

$subject->subject_types()->attach(id_of_your_subject_type); // for example, 
             the id of economics in your subject_type table is 1, then put 1 inside the parenthesis

Upvotes: 1

Vhndaree
Vhndaree

Reputation: 604

Just add eloquent query below

 $subject->save();

Like:

$subjecttype= new SubjectType;
$subjecttype->subjectid= $request->input(‘subjectid’);
$subjecttype->save();

  return redirect()->back()
         ->with('success', 'Úspěšne jsi vytvořil nový předmět.')

Upvotes: 0

Related Questions