phplaraveleloquentdetach

How do delete single row in pivot table with laravel


I want to delete a single row of data in my pivot table. I don't get any error but when try to click on the button. It did not redirect me to anywhere so the delete function is not performed.

pivot table

In the picture above I want to delete the highlighted id for user_id = 3 My scenario is that the user suddenly can't make it to even_id = 6 so the user wants to delete/unjoined the event.

route

Route::get('/user/event/{event}', 'HomeController@destroy')->name('user.event.destroy');

blade

@foreach ($events as $event)
    <tr>
       <td>{{$loop->index +1 }}</td>
       <td>{{$event->event_name}}</td>
       <td>{{$event->event_date}}</td>
       <td>
        <form method="POST" action="{{ route('user.event.destroy',$event)}}">
          @csrf 
          @method('DELETE')
           <a class="btn btn-danger">Unjoined!</a> 
         </form>
         </td>
    </tr>
@endforeach

controller

public function storeEventUser(Request $request)
    {
       $user = User::find(Auth::user()->id);
     //how I storing my pivot data (just to show if anyone asking)
      $user->events()->syncWithoutDetaching([$request->event_id]);
    }


 public function destroy($event)
    {
        $event= Event::findOrFail($event_id);
        $user->events()->detach($event);
        return redirect()->back()->with('success','Deleted.');
    }

Event model

 public function users()
    {
        return $this->belongsToMany(User::class,'event_user','event_id','user_id');
    }

user model

public function events()
    {
        return $this->belongsToMany(Event::class,'event_user','user_id','event_id');
    }

Solution

  • I am adjusting your controller method to use Route Model Binding for simplicity:

    public function destroy(Event $event)
    {
        Auth::user()->events()->detach($event);
        // or from the other side of the relationship
        // $event->users()->detach(Auth::user());
    
        return redirect()->back()->with('success', 'Deleted.');
    }
    

    As stated in the comments you need to adjust your route to Route::delete if you want to use the DELETE HTTP method that your form is spoofing via the @method('DELETE') blade directive.

    Side note:

    Auth::user() returns a User instance so you don't need to query for it again, in your storeEventUser method:

    $user = Auth::user();