Skip to content
This repository has been archived by the owner on Mar 11, 2024. It is now read-only.

Self-referenced relationships create double-reference routes #411

Open
mindfullsilence opened this issue Feb 26, 2023 · 2 comments
Open

Comments

@mindfullsilence
Copy link

mindfullsilence commented Feb 26, 2023

Describe the bug
When creating a relationship on a table that references other records of the same table, the routes generated use the entity name rather than the relationship name. For instance, in the application I'm currently building, I have a "pests" table for defining various insects. Some insects are predators, some insects are prey, and some insects are both. When creating a new insect, the following LogicException appears:
Route pattern "/api/pests/{pest}/pests/{pest}" cannot reference variable name "pest" more than once.

There is also only a single API controller created for handling the requests: PestPestsController, rather than 2 controllers: PestPredatorsController and PestPreyController.

My example is fairly specific, however I could see this being an issue with more common scenarios such as creating taxonomies with parent/child relationships.

To Reproduce
Steps to reproduce the behavior:

  1. Create an entity called "Pest"
  2. Add a "belongsToMany" relationship, using the following settings:

a. Relationship Name: "predators"
b. Pivot Table Name: "predator_prey"
c. Local Model Key Name: "predator_id"
d. Joined Model Key Name: "prey_id"

  1. Once saved, an additional "belongsToMany" relationship is automatically created named "pests", edit this relationship as follows:

First input: "prey"
Second input: "prey_id"
Third input: "predator_id"

  1. Generate the code, run migrations, and open in the browser.
  2. Create a new pest. Once saved, an error will appear:
    Route pattern "/api/pests/{pest}/pests/{pest}" cannot reference variable name "pest" more than once.

Expected behavior
For relationships, I believe the route keys should use the relationship name rather than the entity name, and add the proper binding to the boot method of the RouteServiceProvider if the relationship name is customized as shown in the docs. E.g.:

https://laravel.com/docs/10.x/routing#explicit-binding

// app/Providers/RouteServiceProvider.php
public function boot(): void
{
    // ... 
    Route::model('prey', Pest::class);
    Route::model('predator', Pest::class);
}

The routes should be generated as follows:

        // Pest Prey
        Route::get('/pests/{prey}/pests', [
            PestPreyController::class,
            'index',
        ])->name('pests.prey.index');
        Route::post('/pests/{prey}/pests/{predator}', [
            PestPreyController::class,
            'store',
        ])->name('pests.prey.store');
        Route::delete('/pests/{prey}/pests/{predator}', [
            PestPreyController::class,
            'destroy',
        ])->name('pests.prey.destroy');

        // Pest Predators
        Route::get('/pests/{predator}/pests', [
            PestPredatorController::class,
            'index',
        ])->name('pests.predator.index');
        Route::post('/pests/{predator}/pests/{prey}', [
            PestPredatorController::class,
            'store',
        ])->name('pests.predator.store');
        Route::delete('/pests/{predator}/pests/{prey}', [
            PestPredatorController::class,
            'destroy',
        ])->name('pests.predator.destroy');

Finally, there should be 2 controllers generated: PestPredatorsController and PestPreyController

// PestPredatorsController.php
<?php
namespace App\Http\Controllers\Api;

use App\Models\Pest;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use App\Http\Controllers\Controller;
use App\Http\Resources\PestCollection;

class PestPredatorsController extends Controller
{
    public function index(Request $request, Pest $prey): PestCollection
    {
        $this->authorize('view', $prey);

        $search = $request->get('search', '');

        $pests = $prey
            ->predators()
            ->search($search)
            ->latest()
            ->paginate();

        return new PestCollection($pests);
    }

    public function store(Request $request, Pest $prey, Pest $predator): Response
    {
        $this->authorize('update', $prey);

        $prey->predators()->syncWithoutDetaching([$prey->id]);

        return response()->noContent();
    }

    public function destroy(Request $request, Pest $prey, Pest $predator): Response
    {
        $this->authorize('update', $prey);

        $prey->predators()->detach($prey);

        return response()->noContent();
    }
}
// PestPreyController
<?php
namespace App\Http\Controllers\Api;

use App\Models\Pest;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use App\Http\Controllers\Controller;
use App\Http\Resources\PestCollection;

class PestPreyController extends Controller
{
    public function index(Request $request, Pest $predator): PestCollection
    {
        $this->authorize('view', $predator);

        $search = $request->get('search', '');

        $pests = $predator
            ->prey()
            ->search($search)
            ->latest()
            ->paginate();

        return new PestCollection($pests);
    }

    public function store(Request $request, Pest $predator, Pest $prey): Response
    {
        $this->authorize('update', $predator);

        $pest->prey()->syncWithoutDetaching([$predator->id]);

        return response()->noContent();
    }

    public function destroy(Request $request, Pest $predator, Pest $prey): Response
    {
        $this->authorize('update', $predator);

        $predator->prey()->detach($predator);

        return response()->noContent();
    }
}

Desktop (please complete the following information):

  • OS: application is installed on host machine: macbook pro 2021 M1 Max,
  • project is running using Laravel Sail
  • Browser; chrome
@TiagoSilvaPereira
Copy link
Owner

@mindfullsilence thank you for reporting, I'll check this problem ASAP

@niccolofavari
Copy link

Is there any news about this bug? I have a blocked_by/blocking relationship and this is what is generated in the routes (api and web)

image

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants