Home > Software engineering >  Attachment in Laravel many-to-many relation
Attachment in Laravel many-to-many relation

Time:02-12

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.

Blade

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

Route

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

SubscribeController

public function index($id)
{   
    $user = Auth::user();
    $user->events->attach($id);

    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)?

CodePudding user response:

First, in order to reference the route by name, you need to give it the name subscribe. Docs: https://laravel.com/docs/master/routing#named-routes

Second, you want to add that id route parameter that you are trying to use in your controller. Docs: https://laravel.com/docs/master/routing#required-parameters

So your route should end up looking like this:

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

And then you'll want to call it like this:

<a href="{{ route('subscribe', ['id' => $event->event_id]) }}" 

CodePudding user response:

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

<a href="{{ route('subscribe', $event->event_id) }}" 
>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'])
    ->name('subscribe');

With this route we define:

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