cinameng
cinameng

Reputation: 323

insert relationship with save method using Laravel

I have 2 models with a many to many relationship using Laravel and I want to insert into the relationship table upon using the save method.

I have save method creating the new row for the child and I have access to the parent id.

I need to insert a new row into the relationship table using the parent id that I have access to already along with the id created by the create function within the controller

MODELS

class Objective extends Model
{
           
public function subjects() {
    return $this->belongsToMany('App\Models\Subject');
}}

class Subject extends Model
{
   
public function objectives() {
    return $this->belongsToMany('App\Models\Objective');
}}

The function subject receives the id of the parent from the url and the create function should takes in this id too.

CONTROLLER

class ObjectiveController extends Controller
{
   
  public function subject($id) 
     {
        $subjects = Subject::find($id);
        $objectives = DB::table('objectives')->get();
        return view('admin.objectives.subject',['objectives' => $objectives],['subjects' => 
        $subjects],compact('objectives','subjects'));
     }   


 public function create($id)
    {
        $post = new Objective;
        $post->name = 'NEW OBJ';
        $post->save();
        return redirect('objectives');   
    }
}

ROUTE

Route::get('objectives/create/{id}', [
    'uses' => 'App\Http\Controllers\ObjectiveController@create',
    'as' => 'admin.objectives'
    ]);

VIEW

<a class="card-header-action" href="{{url('objectives/create', ['id' => $subjects->id]) }}"><small class="text-muted">Add New</small></a>

Upvotes: 0

Views: 154

Answers (1)

lagbox
lagbox

Reputation: 50491

You can use attach to add to the pivot table:

...
$post->save();
$post->subjects()->attach($id);

Upvotes: 1

Related Questions