0

I am new to Laravel and web development.

I have two models User and Activity. I want to write a function for User to join an Activity. But I am not sure where to write or should I store in database?

class Activity extends Model
{
    protected $primaryKey = 'act_id';

    public function owner() {
        return $this->hasOne('App\User', 'user_id')->where('owner', true);
    }

    public function user() {
        return $this->belongsToMany('App\User', 'user_id');
    }

    //Not sure if this works?
    public function joinAct($users){
        return $this->users()->attach($users);
    }


}

And the User:

class User extends Model
{
    protected $primaryKey = 'user_id';

    public function activities(){
        return $this->belongsToMany('App\Activity');
    }
}

So where should I write the function join_activity, in Activity model or somewhere else? And I wonder if there is a quick way to test like using php artisan tinker? Thank you!

dexhunter
  • 578
  • 8
  • 24
  • You can check this link it will help https://stackoverflow.com/questions/32059809/laravel-many-to-many-relationship-using-eloquent – Davit Huroyan May 17 '18 at 11:30
  • 1
    $activity->with('user')->where(....)->get() where user is the relation between activity and user model. Or $activity->whereHas('user', function($query){ $query->where(.....);})->get(); let me know if this is what you need and i'll add an answer. I would put it in a controller; join_activity should be updated using sync https://laravel.com/docs/5.6/eloquent-relationships#inserting-and-updating-related-models – Indra May 17 '18 at 11:32
  • Are you asking about using the [query builder (joins) vs eager loading (using relationships in Models)](https://stackoverflow.com/questions/24271416/laravel-eager-loading-vs-explicit-join)? – online Thomas May 17 '18 at 11:48
  • My question is how can I make the `join_activity` function. I am able to define the relationship but I am not sure how and where to write the function. Thanks all. – dexhunter May 17 '18 at 12:35

0 Answers0