skip to Main Content

maybe someone know how to insert pivot table in Laravel 8 automatically every i insert counselings table?

I have Model Counseling n to n Problem,

Input form
enter image description here

counselings table

enter image description here

problems table

enter image description here

Counselings Model

enter image description here

Problem Model

enter image description here

Controller

public function create()
{
    return view('admin.counseling.create', [
        'title' => 'Tambah Bimbingan dan Konseling',
        'students' => Student::all(),
        'problems' => Problem::all()
    ]);
}

public function find_nis(Request $request)
{
    $student = Student::with('student_class', 'counselings')->findOrFail($request->id);
    return response()->json($student);
}

public function store(Request $request)
{ dd($request->all());
    $counseling = new Counseling();
    $counseling->student_id = $request->student_id;
    $counseling->user_id = Auth::user()->id;     
    $counseling->save();

    if ($counseling->save()) {
        $problem = new Problem();
        $problem->id = $request->has('problem_id');
        $problem->save();
    } 
    
}

2

Answers


  1. I would change your store() method to something like this :

    public function store(Request $request)
    { 
        $counseling = Counseling::create([
             'student_id' => $request->student_id,
             'user_id' => Auth::user()->id
        ]);
        if($request->has('problem_id'){
             $counseling->problems()->attach($request->problem_id);
             //return something if problem id is in request
        }
        //return something if problem id is not there
    }
    
    Login or Signup to reply.
  2. You can insert into a pivot table in a few different ways. I would refer you to the documentation here.

    1. Attaching

    You may use the attach method to attach a role to a user by inserting
    a record in the relationship’s intermediate table:

    Example:

    $problem->counselings()->attach($counseling->id);
    
    1. Sync

    You may also use the sync method to construct many-to-many
    associations. The sync method accepts an array of IDs to place on the
    intermediate table. Any IDs that are not in the given array will be
    removed from the intermediate table.

    Example:

    $problem->counselings()->sync($counselingsToSync);
    
    1. Toggle

    The many-to-many relationship also provides a toggle method which
    "toggles" the attachment status of the given related model IDs. If the
    given ID is currently attached, it will be detached. Likewise, if it
    is currently detached, it will be attached:

    Example:

    $problem->counselings()->toggle($counselingsToToggle);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search