To address the requirement where a user can block both entire countries and individual users, you can set up your database tables and relationships as follows:
Database Tables
-
users
-
id -
name -
email - etc.
-
-
countries
-
id -
name -
code
-
-
country_blocks
-
user_id -
country_id
-
-
user_blocks
-
user_id -
blocked_user_id
-
Relationships
- Users can have many Country Blocks and many User Blocks.
- Countries can be associated with many Country Blocks.
Eloquent Models
User Model
class User extends Model
{
public function blockedCountries()
{
return $this->belongsToMany(Country::class, 'country_blocks');
}
public function blockedUsers()
{
return $this->belongsToMany(User::class, 'user_blocks', 'user_id', 'blocked_user_id');
}
}
Country Model
class Country extends Model
{
public function blockingUsers()
{
return $this->belongsToMany(User::class, 'country_blocks');
}
}
Migration Example
Here's how you might define the migrations for the country_blocks and user_blocks tables:
Migration for country_blocks
Schema::create('country_blocks', function (Blueprint $table) {
$table->unsignedBigInteger('user_id');
$table->unsignedBigInteger('country_id');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->foreign('country_id')->references('id')->on('countries')->onDelete('cascade');
$table->primary(['user_id', 'country_id']);
});
Migration for user_blocks
Schema::create('user_blocks', function (Blueprint $table) {
$table->unsignedBigInteger('user_id');
$table->unsignedBigInteger('blocked_user_id');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->foreign('blocked_user_id')->references('id')->on('users')->onDelete('cascade');
$table->primary(['user_id', 'blocked_user_id']);
});
Usage Example
To block a country:
$user->blockedCountries()->attach($countryId);
To block a user:
$user->blockedUsers()->attach($blockedUserId);
This setup allows for flexibility in blocking mechanisms and can be easily extended or modified based on further requirements.