Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

API RESTful Laravel 6.x Best Practice for Many to Many Relatioship

Tags:

rest

laravel

I'm developing an API with Laravel 6.

I've got 2 models:

card -> table cards with card_id ecc.

user -> table users with user_id ecc.

I've defined into models many to many relationships

User.php

public function cards()
{
    return $this->belongsToMany('App\Models\v1\Card');
}

Card.php

public function users() {
    return $this->belongsToMany('App\Models\v1\User');
}

The pivot table is called card_user .

Now I've created routes for single entities:

Route::resource('v1/users', 'v1\UsersController');
Route::resource('v1/cards', 'v1\CardsController');

and I need to develop routes and controller for insert and delete rows from pivot table.

What is the best practice for this issue?

I try to solve this with a special controller that respond to a specific endpoint:

Route::resource('v1/cards/{id}/users', 'v1\CardsUsersController')->only([
    'index', 'store', 'destroy'
]);

But when I need to store information I need to pass the ids of card and user into the URL and as object in post body like so:

[
    'user_id' => $userId,
    'card_id' => $cardId
]

Exists a better way to do this?

Thanks a lot!

like image 333
BobbyLinux Avatar asked Sep 05 '25 06:09

BobbyLinux


1 Answers

You can use Nested Resources as described here: https://laravel.com/docs/6.x/controllers#restful-nested-resources

"Sometimes you may need to define routes to a "nested" resource. For example, a photo resource may have multiple "comments" that may be attached to the photo. To "nest" resource controllers, use "dot" notation in your route declaration:

Route::resource('photos.comments', 'PhotoCommentController');

This route will register a "nested" resource that may be accessed with URLs like the following: photos/{photos}/comments/{comments}."

like image 156
Devon Avatar answered Sep 07 '25 22:09

Devon