Laravel系列包含

时间:2016-11-12 19:50:11

标签: php laravel collections

我在集合https://laravel.com/docs/5.3/collections#method-contains上使用Laravel passport.serializeUser(function(user, done) { done(null, user.id); }); passport.deserializeUser(function(id, done) { User.getUserById(id, function(err, user) { done(err, user); }); }); passport.use(new LocalStrategy(function(username, password, done) { User.getUserByUsername(username, function(err, user) { if(err) throw err; if(!user) { console.log('Unknown user'); return done(null, false, {message: 'Unknown User'}) } User.comparePassword(password, user.password, function(err, isMatch) { if(err) throw err; if(isMatch) { return done(null, user); } else { console.log('Invalid Password'); return done(null, false, {message: 'Invalid Password'}); } }); }); })); router.post('/login', passport.authenticate('local', {successRedirect: '/', failureRedirect:'/users/login', failureFlash:'Invalid username or password'}), function(req, res) { console.log('Authentication Successful'); req.flash('success', 'You are logged in'); res.redirect('/'); }); module.exports = router;方法。但它对我不起作用。

contains

foreach ($this->options as $option) { if($options->contains($option->id)) { dd('test'); } } 看起来像这样:

dd($options);

Collection {#390 #items: array:1 [ 0 => array:3 [ 0 => array:7 [ "id" => 10 "slug" => "test" "name" => "test" "poll_id" => 4 "created_at" => "2016-11-12 20:42:42" "updated_at" => "2016-11-12 20:42:42" "votes" => [] ] 1 => array:7 [ "id" => 11 "slug" => "test-1" "name" => "test" "poll_id" => 4 "created_at" => "2016-11-12 20:42:42" "updated_at" => "2016-11-12 20:42:42" "votes" => [] ] 2 => array:7 [ "id" => 12 "slug" => "test-2" "name" => "test" "poll_id" => 4 "created_at" => "2016-11-12 20:42:42" "updated_at" => "2016-11-12 20:42:42" "votes" => [] ] ] ] } 的结果为dd($option->id);

可能有什么不对?或者有更好的方法吗?

3 个答案:

答案 0 :(得分:22)

  

您应该将键/值对传递给contains方法,这将是   确定集合中是否存在给定的对。

您应该以这种方式使用contains()方法:

foreach ($this->options as $option) {
  // Pass key inside contains method
  if($option->contains('id', $option->id)) {
      dd('test');
  }
}

希望这有帮助

答案 1 :(得分:8)

使用以下内容,告诉Laravel您想要匹配'id':

$options->contains('id', $option->id);

Docs

答案 2 :(得分:0)

foreach ($this->options as $option) {
    if(!$options->flatten(1)->where('id',$option->id)->isEmpty()) {
        dd('test');
    }
}