Attachment In Laravel Many-to-many Relation

- 1 answer

I'm trying to do my first attachment/ detachment. I'm using two tables, user, event, and its pivot, event_user. For this one, I needed to do a button to subscribe the user to an event, so my teacher told me to use an and route it to the method subscribe. At this moment, the error that comes up is.

Route [subscribe] not defined.


<a href="{{ route('subscribe', $event->event_id) }}" 
    class="btn btn-primary btn-lg">Subscribe</a>


Route::get('/subscribe', [SubscribeController::class, 'index']);


public function index($id)
    $user = Auth::user();

    return view('index');

I tried putting URL instead of the route in the , and it goes to /subscribe, but comes to an error that says -> Too few arguments to function 0 passed and exactly 1 expected.

I did a dd() in the component to see if the event id was the correct one, and it was. Also, apart from these errors, how can I route a method without changing the route? Can I do it using the indexController (because it's in the index where these events are located)?



Firstly in your blade view file you are trying to generate url using route helper like this

<a href="{{ route('subscribe', $event->event_id) }}" 
class="btn btn-primary btn-lg">Subscribe</a>`

The way you call the route helper we can supposed this

  1. You have already define a route in your web.php file which is named subscribe
  2. and that route have paramater

But in your web.php file you have this route

Route::get('/subscribe', [SubscribeController::class, 'index']);
  1. This route doesn't have any name.
  2. And it doesn't expect any parameter

To fix that you should only change the way you have define you route in the web.php file like this

Route::get('/subscribe/{id}', [SubscribeController::class, 'index'])

With this route we define:

  1. id as a required parameter
  2. And the route is named subscribe