简体   繁体   中英

How to compare id's in many to many relationship

I have 'article' and 'user' models with m2m relationship (pivot table with user_id and article_id columns). In ArticleController i need to check is user the one of authors of the article to have access perform update/delete operations with article. I can take currently logged user id from auth->user()->id.

In this case you need to use Laravel policies
i suggest you to take a look at this documentation
Authorization

If you using standard Eloquent-relationship as per https://laravel.com/docs/5.6/eloquent-relationships#many-to-many

Just simply get the article first then check if it has relation with the authenticated user.

$article = Article::find($id);
if ($article->users()->where('id', Auth::user()->id)->get()->count() ) {
     //your code
}

I used policies with such algorithm inside. Thx for help.

public function update(User $user, Article $article){
    //All articles id where user is author.
    $userArticles = UserArticle::where('user_id', $user->id)->get();

    $confirmFlag = false; //check flag.
    //We compare article ids that belong to user with article id that we want to edit.
    foreach ($userArticles as $userArticle) {
        if ($userArticle->article_id != $article->id) {
            $confirmFlag = false;
        } else {
            $confirmFlag = true;
            break; // if we found that article that we want to edit
            // is belong to user then we break our foreach with $confirmFlag=true.
        }
    }
    return $confirmFlag == true ? true : false;
}

According to your own answer , I want to give you a better approach ...

public function update(User $user, Article $article){
//All articles id where user is author.
  $userArticles = UserArticle::where('user_id', $user->id)->where('article_id', $article->id)->first();

  return $userArticles === null ? false : true;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM