HarbzAli's avatar

BelongsToMany relation for 3 models

Hello I have 3 models Location, Car, User i have made a belongstomany relation between car and user to get with the garage

Schema::create('garage', function (Blueprint $table) {
            $table->id();
            $table->foreignIdFor(\App\Models\User::class)->constrained()->cascadeOnDelete();
            $table->foreignIdFor(\App\Models\Car::class)->constrained()->cascadeOnDelete();
            $table->foreignIdFor(\App\Models\Location::class)->constrained()->cascadeOnDelete();
            $table->tinyInteger('damage')->default(0);
            $table->string('plate', 8)->nullable();
            $table->timestamps();
        });

i got everything works perfect besides the location, i can not get the location of each car, please help User model:

public function cars(): \Illuminate\Database\Eloquent\Relations\BelongsToMany
    {
        return $this->belongsToMany(Car::class, 'garage', 'user_id', 'car_id')->withPivot('damage', 'plate', 'location_id')
                ->withTimestamps();
    }

Car model:

public function users(): \Illuminate\Database\Eloquent\Relations\BelongsToMany
    {
        return $this->belongsToMany(User::class, 'garage', 'car_id', 'user_id')->withPivot('damage', 'plate', 'location_id')->withTimestamps();
    }

    public function location(): \Illuminate\Database\Eloquent\Relations\BelongsTo
    {
        return $this->belongsTo(Location::class, 'location_id');
    }

Location model:

public function cars(): \Illuminate\Database\Eloquent\Relations\HasMany
    {
        return $this->hasMany(Car::class, 'location_id');
    }
0 likes
1 reply
kevinbui's avatar

Which errors do you have? where is that?

Please or to participate in this conversation.