Solution:
Assuming that community users is the model that maps your many to many relation table, you should specify the correct table name in the database for that model.
class CommunityUsers extends Model
{
/**
* The table associated with the model.
*
* @var string
*/
protected $table = 'community_users';
}
Also, keep in mind that Eloquent doesn’t support composite primary keys, so you have to set either community_id
or user_id
as primary key in the CommunityUsers
model to use the find()
method on it, otherwise Laravel would search by the id
column.
I’d rather insert a new primary auto increment column to the relation table, and retrive a spceific community with a where filtering like this:
CommunityUsers::where('community_id', $id)->first();
Note: You could also make that filter as a CommunityUsers
scope method.
Furthermore, notice that you relation from Users
to CommunityUsers
is a one to many relation (one User
maps to many CommunityUsers
pair ([community_id, user_id]))
Rethinking the relation mapping
If you consider the three tables, that can be modeled as a many to many relation among Users
and Communities
.
The relations should be:
Model: User
class User extends Authenticatable
{
public function communities()
{
return $this->belongsToMany(EventCategories::class, 'community_user', 'user_id', 'community_id');
}
}
Model: EventCategories (Assuming that is your Community model)
class EventCategories extends Model
{
public function users()
{
return $this->belongsToMany(User::class, 'community_user', 'community_id');
}
}
Note: The code above might need some tweaking based on your models and their table definitions.
After that relation definition you can use it directly on the EventCategories
model:
public function communityBySlug($slug){
$eventCategory = EventCategories::with('users')
->whereSlug($slug)
->first();
return Response::json(
[
'data' => $eventCategory,
'community_followers' => $eventCategory->users
]
);
}