0

I try to delete an item form a pivot query , and i'm not sure if i do the right method .

Here my view with some "football stades" for a structure (club)

structure can have many stades and stades have many structures

here my model Stade :

public function structures()
    {
        return $this->belongsToMany('App\Structure');
    }

here my model Structure :

 public function stades(){

        return $this->belongsToMany('App\Stade');

    }

My pivot table is like:

structure_id 
stade_id




@foreach($club->stades as $stade)
                        <tr>
                            <th>{{$stade->lb_nom}}</th>
                            <th>{{$stade->adresse_stade}}</th>
                            <th>{{$stade->ville_stade}}</th>
                            <th>{{$stade->cd_post_stade}}</th>
                            <th>{{$stade->tel_stade}}</th>
                            <th>
                                {{ Form::open(['method' => 'DELETE', 'route' => ['club.stade.destroy', $club->id , $stade->id ]]) }}
                                {{ Form::submit('Delete', ['class' => 'btn btn-danger']) }}
                                {{ Form::close() }}


                            </th>
                        </tr>
                        @endforeach

I can insert a new stade to a structure without any problems

 public function store(Request $request , $id){

    $stade_structure = new ClubStade;

    $structure =  Structure::findOrFail($id);

    $stade_structure->structure_id = $structure->id;

    $stade_structure->stade_id = $request->input('stade_id');

    $stade_structure->save();

        return back()->with('status', "Un nouveau stade à été ajouté pour votre Club ! ");
    }

but now i would like to detach or delete the record from the table . do i need to make a delete function ?

thanks a lot in advance

1
  • You may pass an array of id's to detach() that you want to delete from the pivot table. like $stade->structures()->detach([1, 2, 3...]) Commented Mar 30, 2017 at 11:56

1 Answer 1

1

detach() is what you're looking for:

This will delete item only from pivot table.

If you want to delete relating model then you have to use delete method. Click here for more detail

Sign up to request clarification or add additional context in comments.

1 Comment

public function detach($id){ $stade = Stade::findOrFail($id); $stade->structures()->detach(); return back()->with('status', "Stade supprimé de votre Club"); }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.