Support the ongoing development of Laravel.io →
posted 7 years ago
Eloquent
Last updated 2 years ago.
0

If each user can have many settings and each setting can belong to many users then the following is correct database design. A setting should belong to a setting type and therefore I've moved the foreign key to the settings table.

    Schema::create('users', function (Blueprint $table) {
        $table->increments('id');
        $table->string('firstname');
        $table->string('surname');
        $table->string('address')->nullable();
        $table->string('city')->nullable();
        $table->string('country')->nullable();
        $table->string('postcode')->nullable();
        $table->string('email')->unique();
        $table->string('password');
        $table->rememberToken();
        $table->timestamps();
    });
    Schema::create('settings', function (Blueprint $table) {
        $table->increments('id');
        $table->string('value');
        $table->timestamps();

        $table->integer('type_id')->unsigned();
        $table->foreign('type_id')->references('id')->on('setting_types');
    });
    Schema::create('setting_types', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->timestamps();
    });
    Schema::create('users_settings', function (Blueprint $table) {
        $table->timestamps();

        $table->integer('user_id')->unsigned();
        $table->integer('setting_id')->unsigned();

        $table->foreign('user_id')->references('id')->on('users');
        $table->foreign('setting_id')->references('id')->on('settings');
    });

On your User::class add the relationship:

    public function settings()
    {
        return $this->belongsToMany(Setting::class, 'users_settings');
    }

On your SettingType::class add the relationship:

    public function settings()
    {
        return $this->hasMany(Setting::class, 'type_id');
    }

On you Setting::class add the relationships:

    public function type()
    {
        return $this->belongsTo(SettingType::class, 'type_id');
    }
    public function users()
    {
        return $this->belongsToMany(User::class, 'users_settings');
    }

To get the json you wanted, you could do:

$settings = Setting::with(['users', 'type'])->get();

return response()->json($settings);
Last updated 7 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.